Tuesday, December 03, 2013

C# - Owner Drawn ComboBox Control

1. Introduction to Owner Drawn Controls

When we place a control on the form, the control’s appearance is usually decided by the control itself. Let us say for example that you placed a List Box control on the form, the appearance of ListBox control is drawn by the dot net frame code written for that control itself. That means, the ListBox class or its parent class can take the responsibility of drawing the control. This is the normal behaviour for almost all the control.

In the same case, let us say that the Form performs the drawing of each ListBox item with a double lined red border around each item. In this case, the Form is called as Parent or Owner of the ListBox and ListBox control is seen as "Owner Drawn Control". In easy words, the Form (Owner of the ListBox) draws the ListBox Items. In this article, we will see how de we create an Owner Drawn ComboBox.



2. About the Example

Below is the Screenshot of the application that we are going to create:


In the above screenshot, the default appearance of the ComboBox is changed to display the color boxes. This ComboBox is partly drawn by the Form. That is, the ComboBox with a Down Arrow is drawn by the control itself. The Form draws the content of the ComboBox when it is dropped down.

The Owner of the ComboBox in the example will perform the Following drawing:


  1. Draws the Color Rectangle
  2. Draws Text String next to the colour rectangle
  3. Draws the Red Border around the selected Item


Once the colour is selected, the text typed in the textbox will appear in the selected colour.


3) About Owner Draw

The control Listbox, Combobox, TabControl and TreeView Control supports Owner Draw. All these controls have the property called "DrawMode", which specifies what kind of owner drawn will be used. The ComboBox as well as ListBox supports three kinds of DrawMode and these modes are:


  1. Normal
  2. OwnerDrawFixed
  3. OwnerDrawVariable

3.1 Normal Mode



This is the default drawing mode set to a ListBox and ComboBox control. In this Mode, windows take the responsibility of drawing the control and each item contained in it.

3.2 OwnerDrawFixed



When this mode is set to the DrawMode property, the owner will draw the control by handling the "DrawItem Event". Each item will have fixed height.

3.3 OwnerDrawVarible



In this mode, the owner will draw as well as measure the individual item. So we can say that each item can have different height. When this Mode is set, the owner of the control should provide "DrawItem" and "MeasureItem" event handlers. In the MeasureItem handler, each item’s height will be measured and in the DrawItem each item will be drawn. The MeasureItem handler will be called only during the control initialization. But, the DrawItem will be called for each item when the drop arrow is clicked.

For this example, we need to set the OwnerDrawFixed to the DrawMode property as shown below:





4. Coding – Arranging the Form

1) In the Form Load handler function, populate the combo box with the strings that represents the colour. Below is the code:

//Snippet 02: Populate the Owner Drawn Combo box
private void frmComboSample_Load(object sender, EventArgs e)
{
    OwnerDCombo.Items.Add("Red");
    OwnerDCombo.Items.Add("Blue");
    OwnerDCombo.Items.Add("Green");
    OwnerDCombo.Items.Add("Chocolate");
    OwnerDCombo.Items.Add("Gold");
    OwnerDCombo.Items.Add("Purple");
    OwnerDCombo.Items.Add("LigntSeaGreen");
}

2) Next, write a function that returns the "System.Drawing.Colour" for a given colour name. Below is the function:

//Snippet 03: Get the Colour selected in the Combo box
public Color GetColor(String ColorName)
{
    Color col = Color.Black;
    if (ColorName == "Red")
    {
        col = Color.Red;
    }
    else if(ColorName == "Blue")
    {
        col = Color.Blue;
    }
    else if(ColorName == "Green")
    {
        col = Color.Green;
    }
    else if(ColorName == "Chocolate")
    {
        col = Color.Chocolate;
    }
    else if(ColorName == "Gold")
    {
        col = Color.Gold;
    }
    else if (ColorName == "Purple")
    {
        col = Color.Purple;
    }
    else
    {
        col = Color.LightSeaGreen;
    }

    return col;
}

3) In the ComboBox Selection change, the selected colour is retrieved to set the "ForeColor Property" of the textbox. To retrieve the colour the previously written function "GetColor() method" is used. Below is the code for that:

//Snippet 03: Set the Textbox colour based on the Combo Selection
private void OwnerDCombo_SelectedIndexChanged(object sender, EventArgs e)
{
    if (OwnerDCombo.SelectedIndex == -1)
        return;

    String strColor = (String)OwnerDCombo.Items[OwnerDCombo.SelectedIndex];
    TxtNotePad.ForeColor = GetColor(strColor);
}

5. Coding – DrawItem Handler

1) As already specified, <controlname>_DrawItem will perform the drawing for each item present in the combo box. This handler will be called for each item present in the combo box (When DrawMode is not normal). In this handler, first, we retrieved the Color Object and colour name by making use the index reported by the "DrawItemEventArgs".

private void OwnerDCombo_DrawItem(object sender, DrawItemEventArgs e)
{

//Snippet 04.1: Get the color currently selected in the Combobox
String strColor = (String) OwnerDCombo.Items[e.Index];
Color Selected_Color = GetColor(strColor);
String color_name = Selected_Color.Name;

2) As the function takes the responsibility of drawing the content of each combo box item, should perform the background drawing. First graphics object called “grp” is retrieved and then "DrawBackGround() method" is called on the DrawItemEventArgs. This will enable current item highlight when you hover the mouse on combo box items. Below is the code:

//Snippet 04.2: Get the Graphics from the Argument
Graphics grp = e.Graphics;
e.DrawBackground();

3) The DrawItemEventArgs supplies bounding box of the current combo box that needs to be drawn through its member called Bounds. A one-pixel indent is applied on top, left and bottom and the Width to be drawn as set as 20 pixels. Based on this, a Rectangle “rct” is formed. Through the already retrieved Graphics object, the rectangle is drawn. Below is the code:

//Snippet 04.3: Get the bounding rectangle to draw the item
int Rect_left = e.Bounds.X + 1;
int Rect_top = e.Bounds.Y + 1;
Rectangle rct = new Rectangle(Rect_left, Rect_top, 20, e.Bounds.Height - 2);
grp.DrawRectangle(Pens.Black, rct);

When we run the application at this stage, it looks like as shown below:



4) Once the bounding rectangle is formed, the rectangle is filled with the colour reported by the event argument. To perform the fill operation on the rectangle, brush object is formed from the colour object associated to the current item that needs to be drawn. Below is code for filling the rectangle using GDI+ brush:

//Snipper 04.4: Create a Solid Brush and Fill the Item Rectangles
SolidBrush brush = new SolidBrush(Selected_Color);
grp.FillRectangle(brush, rct);

Running the application looks like below now:



5) OK. Now we have colour rectangles in the combo box. Next, we should add the text that belongs to the colour rectangle. To draw the text, we should have offset from the left of the combo box as the rectangle is already occupying the left portion. To apply offset for drawing the text, we should perform the summation of, left offset already done to draw the rectangle (Shown as 1), the rectangle width and the new offset from the right of the colour rectangle (Hardcoded as 2). The summation will give from where (On the left side) the drawing of the text should take place. Below picture explains this:




Now in the code, we made a call to "DrawString() method" on the retrieved grp object. While calling the function, the left location of the string to be drawn is calculated based on the color rectangle’s dimensions, which already explained. Below is the code that draws the text next to the color Rectangle:

//Snippet 04.5: Create a Brush for drawing the texts
SolidBrush textb = new SolidBrush(Color.Black);
grp.DrawString(color_name, e.Font, textb, Rect_left + rct.Width + 2, Rect_top);

Running the application at this  stage look like below.



6) At last, we have to draw a bounding rectangle for the selected combo box item. By performing Bitwise AND (&) with “e.state” we can tell that the current item we are drawing is in selected stated or Not. When an item is in Highlighted state, a bounding rectangle around it is drawn in the Red Rectangle colour. To erase previously drawn red bounding rectangle, the drawing in the else portion is performed. Below is the code:

//Snippet 04.6: Draw a Border around the Selected Item
if ((DrawItemState.Selected & e.State) == DrawItemState.Selected)
{
    grp.DrawRectangle(Pens.Red, e.Bounds);
}
else
{
    grp.DrawRectangle(Pens.White, e.Bounds);
}

The below given video shows the completed application:


Source Code: Download

Monday, November 11, 2013

[ MFC ] - Creating custom Mapping Mode in Visual C++ using MM_ISOTROPIC

1. Introduction


In the previous MFC Article, we examined how the Mapping Modes works while performing the drawing operation. In this example, we will see how do we set the custom mapping modes. Out goal is below:
1) Set mapping mode so that the horizontal logical unit is 1 cm. Simply, 1 Unit = 1 c.m in X axis
2) Also, 1 Unit = 1 c.m in Axis.
3) Positive X is towards left
4) Positive Y is going Upwards
5) The Drawing origin should be in screen center


2. The Custom Mapping Mode


To achieve the above we need to use the Custom Mapping mode. From the previous article, you may now know that the mapping modes MM_ISOTROPIC, MM_ANISOTROPIC are custom mapping modes. In MM_ISOTROPIC mode, both X and Y-axis represents the same unit of measure. That is if X-axis represents 1 logical unit as 1 m.m then Y-axis also represent 1 logical unit as 1 m.m. In our example, we are going to use the MM_ANISOTROPIC mode.


3. About the Example


Have a look at the below depiction:




We are going to draw X Axis and Y Axis and then draw an ellipse. The ellipse will have 8 cm major axis and 4 cm minor axis when measured after having the hardcopy. So to achieve this drawing, we should set a mapping mode that will see one unit as 1 centimeter. Also, note that the Origin should be at the center of the screen.

OK. Let us walk through how do we create this example.


4. Coding the Example


1) Create a Single document interface application (SDI) and in the OnPaint Handler, we are going to perform the drawing specified above. First, we need to set the mapping mode as ISOTROPIC and ANISOTROPIC. In this example I specified the ISOTROPIC mapping mode as both X and Y-axis has the same unit of measure that is 1 logical drawing unit is 1 centimeter. Below is code that set the mapping mode:

CPaintDC dc(this); // device context for painting
dc.SetMapMode(MM_ISOTROPIC);


2) Once the mapping mode is set the screen resolution in terms of mm is returned using the GetDeviceCaps function by passing the HORZSIZE, VERTSIZE. The size returned in mm is based on the current resolution. The screen size in mm is stored in the variables width_in_mm and height_in_mm.

//Sample 01: Returns the Dimension in MM
int width_in_mm = dc.GetDeviceCaps(HORZSIZE);
int height_in_mm = dc.GetDeviceCaps(VERTSIZE);

The picture shown below tells that the 1 pixel is represented as 0.3525 mm approximately.

3) Once we have Screen resolution in mm, we need to get the screen resolution in pixels. We use the same GetDeviceCaps function to get the screen resolution in pixels. Below is the code:

//Sample 02: Return the dimension in pixels
int width_in_pixels = dc.GetDeviceCaps(HORZRES);
int height_in_pixels = dc.GetDeviceCaps(VERTRES);

4) Have a look at the below picture:
From the above picture you can see how the Window and "Viewport Extends" works together. Imagine that the gray lines 1 unit and 1 unit is one pixel. The Red line shows how the window is divided by logical measure, say, for example, imagine like this, the screen dimension of 7x5 mm is divided as 4 horizontal extends and 3 vertical extends. This same technique can be used in the below-given code.

//Sample 03: How the screen divided in terms of Logical Units.
//For Example, if horz size returned is 500 mm,
//the window is divided into 50 logical extents.
dc.SetWindowExt(width_in_mm/10, (-1 * height_in_mm)/10); // 10 MM = 1 Unit or 1 CM = 1 Unit

//Sample 04: How the screen divided in terms of pixels
dc.SetViewportExt(width_in_pixels, height_in_pixels);

In the above code we specified the following unit of measures:
Device Coordinate system’s unit of measure is done by the SetViewportExt function call. Let us say the resolution is 800x600, so the screen is divided as "800 extents" horizontally and "600 extents" vertically. That means each unit represents pixels; for example, if I say 10 unit in device coordinate then it is 10 pixels. For same 800x600 resolution, the screen size measured is 282x212 mm. Now, using the SetWindowExt function call, we divided the screen width as 28 extents and screen height as 21 extents. This way each unit measures 1 cm in the logical unit (Put down your calculator and I agree there is a slight precision loss).

OK. What is the importance of specifying the extents? Let us start with a detailed explanation that may help you understand the coordinate transformation in terms of Pixels versus Logical units. From the above picture, the Device Coordinate System uses the gray lines and the Logical Co-ordinate system uses Red lines as a unit of measures. MFC Framework and Win32 API uses both the coordinate systems. For example, the WM_LBUTTONUP uses the device coordinate system to specify the mouse cursor location in terms of (x, y) pixels. Whereas, the drawing functions exposed by the CDC (Device Context) expects the Logical coordinate system. Now, think how a user can draw a 10 cm line by using the mouse.

In this case, a coordinate conversion is required. Your code may go like this:
1) The mouse events capture the Line start and end
2) Start point and end points are converted to Logical unit from Device unit
3) These converted points (Dimensions) passed to the Line Drawing functions

Note that at the first step itself showing the line dimension (In logical unit) helps the user to draw 10 cm line. Now you may have an idea of coordinate space conversion. Two kinds of conversion are possible and they are:
a) Device Space to Logical Space
b) Logical Space to Device Space

In my previous article I specified that except MM_ISOTROPIC and MM_ANISOTROPIC, all co-ordinate have the valid mappings. These two mapping modes are custom mapping modes and that means you decide the mapping between Logical and Physical unit. I am moving to the next coding part and at the end of the article, we will derive the coordinate transformation formula.


5) Next, we shifted the viewport origin towards the center of the screen. Below is the code for it.

//Sample 05: Set Viewport Orgin to the Screen Center
CRect rct;
GetClientRect(&rct);
dc.SetViewportOrg(rct.right/2, rct.bottom/2);


6) Once the drawing origin is shifted to the screen center, the x-axis and y-axis are drawn using the MoveTo, LineTo functions. Next using the device context an ellipse is drawn to the screen. Now all the units specified here are in Centimeter.

//Sample 06: Draw the Axis
dc.MoveTo(-10,0);
dc.LineTo(10,0);
dc.MoveTo(0,-8 );
dc.LineTo(0,8);

//Sample 07: Draw the Ellispse
dc.Ellipse(0, 4, 8, 0);


 Source Code : Download



Sunday, October 20, 2013

ASP.Net - Displaying and Manipulating Data Using FormView Control

1. Introduction

In this example, we will see how do we make use of FormView control to retrieve the data from the database. We are going to use SQLDataSource Control to supply the data for the FormView control. We will also have look at modifying the FormView templates.

The FormView control allows you to place the data bound controls wherever you want. It is just like designing the form for calculating the Electricity Bill based on unit consumption. Now think of getting the table columns from the database and placing that freely wherever we want on the web page. This is what achieved by the FormView control. Have a look at the below picture:


The three column data can be placed wherever we want. The FormView control allows editing as well as inserting the data as well. The underplaying Data Source should provide the support for it. A FormView control has templates associated with it. These templates are:

  1. Header Template
  2. Footer Template
  3. Edit Item Template
  4. Insert Item Template
  5. Item Template
You can modify each template and arrange the controls the way you want. Header and Footer templates are always displayed. Item Template is used to display the data. Edit Template is used when we want to modify the Data and Insert Template is used when we want to do the data insertion. In our example, we are going use the FormView Control to display the data. Okay, let us start with the example.


2. About the example

The Example application, which uses the FormView control, is shown below:


Using the Numbered links user can navigate through the records. The header and Footer will be displayed statically and it will not get changed when we navigate between the records. Data Manipulation can be done using the Edit, Delete and New Links. The Items marked in green boxes are bound to the database and when the user makes record navigation, the content in the Green Boxes get changed.



3. Configure Data Source

A DataSource control should be configured to supply the data for the FormView control. In our example, SQLDataSource control is configured to supply the data to the FormView control.

The FormView control enables data editing as well and to allow data editing the underlying data source should also support the data manipulation. In our example, SQLDataSource control is configured to retrieve the data from the Titles table of the Pubs database. Also, the SQLDataSource control is configured in such a way that it can perform the data manipulation as well. The below-given video shows how the SQLDataSource is configured.

Video 1: Configuring the Data Source




4. Configuring the FormView Control – Header, Footer

Once the FormView control is placed on the Default.aspx page, using the Quick Task Options, the SQLDataSource created in the previous section is linked to it, using the Choose Data Source option. Have a look at the FormView control shown below:


In the above picture:

1: Shows the FormView Control.
2: Text added using the Header Template. This text will be constantly displayed when a user moves from one page to other using numbered links at the lower left of the form.
3: Text added using the Footer Template. This behaves same as Header template.
4: This shows that user can go to different records. This is done using the paging option in Quick Task List.
5: These options will be displayed when you selected data source is configured for editing the data.

The below video explains how do you Configure header and footer template.

Video 2: Configuring the FormView control





5. Item Template, EditItem Template and InsertItem template

When a user moves between the records by clicking the numbered link at the end of the control, the FormView will be in ReadOnly Mode. When the FormView control is displayed in the ReadOnly mode the Item Template is used. When user clicks the link “Edit” the EditItem template get displayed. The same way InsertItem template gets displayed when the “Insert” link is clicked. Each template can be edited as a HTML page.

In the Template editing mode, you can place a completely different control and bind that to the control. The below-given video shows editing the InsertItem and EditItem templates.

Video 3: Completing the FormView Control



Source Code : Download



Monday, August 19, 2013

C# - Understanding GDI+ with Pen and Brushes of Solid, Hatch, Gradient types

1. Introduction

In this article we will have a look at how do we perform the drawing operation using the GDI plus functions available with DotNet. GDI stands for "Graphical Device Interface" and using that you can create rich drawing applications, show useful information on the form as a drawing say for example showing a pie chart of sales on past 5 years.

In this article I will show how do you perform the drawing using Pen and Brushes.



2. What is Pen and Brush in C#?

A "Pen" is a graphics object, which can be used to perform line drawing. A pen has the properties like the color of the Pen and thickness of the pen. A brush is also a graphics object, which can be used to paint the region. Suppose if you want to fill the area you can use the Brush. Think about Painting a door, a wooden plate etc.

In this article I will show how to use the "Plain Solid Brush", "Gradient Brush" and "Hatch brush".



3. About the Finished Example

Below is the Screen shot of the finished application:



The Black screen is the Panel control and it is used in this example as a drawing canvas. When the Fill Brush is not enabled whatever you draw is drawn using only the Pen. That means you see the drawing outline that is Rectangle outline in our example. You can switch between Solid Brush and Advanced brush using the Advanced Brush checkbox. When the checkbox is enabled, you see the advanced brush options that can be toggles between Hatch and Gradient using the Toggle switch shown as seven in the screen shot above.



4. Drawing the Rectangle Object

To draw a rectangle in GDI+ we need its size and position. So in the first part of the development, we placed the controls to collect the Rectangle’s position and the size (Section 1 and 2 in the screenshot above). Then the rectangle is drawn in the Panel named as DrawingCanvas.

1) First the required namespace to perform the 2d drawing is placed in the using directive as shown below. Note that this required when we want to use the rich functionalities of the GDI+

//Sample 00: Required Name Spaces
using System.Drawing.Drawing2D;

2) Then a Rectangle object is created and its size and position are filled by the user-supplied values.
//Sample 01: Create the rect object.
Rectangle rect = new Rectangle();
rect.X = Int32.Parse(txtX.Text);
rect.Y = Int32.Parse(txtY.Text);
rect.Width = Int32.Parse(txtWidth.Text);
rect.Height = Int32.Parse(txtHeight.Text);

3) The black screen that you see in the Sample application screenshot is a Panel Control. The "CreateGraphics() method" will return the graphics object. You can use this method on any window objects like Panel, Form or even controls like textbox, listbox etc. In our case, we asked the Panel Control to retrieve the Graphics object from it. And this object is stored in grp of type Graphics. Once the Graphics object is ready, a Pen is created with a color of Goldenrod, which is a preset color. You can see all the present color by Typing Color dot. Below is the code:

//Sample 02: Get the Graphics from the Canvas(Panel) and Create the pen
Graphics grp = DrawingCanvas.CreateGraphics();
Pen pen = new Pen(Color.Goldenrod);

4) Before performing the Drawing (Note we write all these code in the Draw Button click handler), we clear any previously drawn by calling the Clear method of the Graphics object. Then the Rectangle is drawn with the user supplied Rectangle demotions.

//Sample 03: Clear the Graphics and Draw Rectangle
grp.Clear(Color.Black);
grp.DrawRectangle(pen, rect);

Test Run 1: The Video Explains how the sample looks when user feeds different values for the Rectangle. You can learn how Position and Size of Rectangle used in drawing a rectangle in the below video.

Video 1: Explains how Rectangle is Drawn





5. The GDI+ Pen

Using the pen object we can defines the drawing line color and its thickness. In our example application, controls marked by the number 3 are used to create a pen. In the previous section we created a pen just by specifying the color. This line of code is expanded to use the user selection on the form. Let us have look at the code for creating and using the Pen object:

1) First two variables are declared. The variable pencolor is used specify the color of the pen and this variable will be filled with the user selected color. The variable thickness is used to specify the pen thickness when we create the pen object.

//Sample 03: Create the Pen
Color pencolor;
int thickness;

2) Based on the user selected Pen color using the Radio buttons, the pencolor variable is filled by taking predefines color values like Color.Pink. The code is below:

//3.1: Decide Pen Color
if (radGolden.Checked == true)
    pencolor = Color.PaleGoldenrod;
else
    pencolor = Color.Pink;


3) Similarly, the thickness value also filled by the user selected line thickness combo box option. The pen thickness in our example has three standard thicknesses, but you can specify any float value to create a pen thickness. Below is code that stored the pen thickness:

//3.2: Decide Pen Thickness
if (rad1.Checked == true)
    thickness = 1;
else if (rad5.Checked == false)
    thickness = 3;
else
    thickness = 5;

4) Finally a pen object is created making use of the pencolor and thickness variables populated previously. This pen object can be supplied to Graphics functions so that the function uses this new pen whenever it performs a line drawing.

Pen pen = new Pen(pencolor, thickness);

Below is some of the Pen and look at the Lines that forms the Rectangle:

Video 2: Creating a Pen




6. The GDI+ Brushes

In this example I am going to show you different types of Brushes. Imagine a brush that you use to paints the walls of your house. The GDI+ brushes can also be used similar to this. We draw something using the pens that defines outer lines and then paints (Using brush) the region inside the region formed by the pens. But you are not restricted like brush can be used only with pens.

The types of brush that you are going to see here are:

  1. Simple Solid Brush
  2. Gradient Brush
  3. Patterned Brush

The Simple Solid brush fills the color in plain solid color. The Gradient Brush fills color between two colors applying the linear transformation from one color to another color. The hatch brushes fills the region with a given pattern. All these types of brushes in effect are shown in the below picture:


OK. Let us see, how do we achieve it. 

1) Below is the CheckedChanged event handler for the checkbox marked as four in the first picture of the article. In this handler we decide to enable or disable the entire GroupBox that belongs brushes.

//Sample 05: Enable the Brush Group Box
private void chkBrushEnable_CheckedChanged(object sender, EventArgs e)
{
    if (chkBrushEnable.Checked  == true)
        grpBrush.Visible = true;
    else
        grpBrush.Visible = false;
}

2) During the Form load, by default only the Solid brush option will be displayed. The user should check the Advanced Brush check box to enable the Gradient/Hatch Brush options. This code is below:

//Sample 06: Disable Advanced Brush Option
private void frmRectDraw_Load(object sender, EventArgs e)
{
    grpBrushAdv.Visible = false;
}

3) When the Advanced brush is displayed, solid brush is hidden. The same way, when the solid brush is displayed the advanced brush is hidden. This is done through CheckedChanged event handler of the Advanced Brush check box. The code for that is shown below:

//Sample 07: To show or Hide Advanced brush option
private void chkAdvBursh_CheckedChanged(object sender, EventArgs e)
{
    if (chkAdvBursh.Checked == true)
    {
        grpBrushAdv.Visible = true;
        grpBrushSolid.Visible = false;
    }
    else
    {
        grpBrushAdv.Visible = false;
        grpBrushSolid.Visible = true;
    }
}

4) In the Example application screenshot, the control item marked as 7 is a Label Control. This label control is used as the toggle button which alternate between and Gradient and Hatch. When the control label shows as Gradient then the user will see controls relevant to Gradient Brush. And, the same hold true for the Hatch brush also. We specify different captions for the color based radio buttons based on the current brush mode (Gradient or Hatch). The controls specific to the hatch brush will be shown/hidden based on the current brush mode. This kind of work is done in the click event handler for the Label control:

//Sample 08: Show the controls relevent for Hatch brush or
// Gradient Brush
private void lblHatchGr_Click(object sender, EventArgs e)
{
    if (lblHatchGr.Text == "Gradient")
    {
        lblHatchGr.Text = "Hatch";
        lblHatPat.Visible = true;
        radHatTypeHorizontal.Visible = true;
        radHatTypeVerticle.Visible = true;
        radHatTypeWave.Visible = true;
        radHatTypeHorizontalBrick.Visible = true;
        HatchGB1.Text = "Forecolor";
        HatchGB2.Text = "BackColor";
    }
    else
    {
        lblHatchGr.Text = "Gradient";
        lblHatPat.Visible = false;
        radHatTypeHorizontal.Visible = false;
        radHatTypeVerticle.Visible = false;
        radHatTypeWave.Visible = false;
        radHatTypeHorizontalBrick.Visible = false;
        HatchGB1.Text = "From";
        HatchGB2.Text = "To";
    }
}

5) Below is the function GetSolidBrushColor_FromUI that gets the color for the solid brush. This function reads the user selected radio button for the solid brush color and assign that to the out parameter passed in as color. Note that the out parameter guarantees the caller that the function will definitely assign a value in the color parameter and the caller no need to initialize the value. The function is below:

//Sample 09: Get Solid Brush color from UI
private void GetSolidBrushColor_FromUI(out Color color)
{
    if (radSolBrRed.Checked == true)
        color = Color.Red;
    else if (radSolBrGreen.Checked == true)
        color = Color.Green;
    else
        color = Color.Blue;
}

6) Look at the sample application screenshot labeled at 6, the GroupBox names “From” and “To” will be changed as ForeColor and BackColor when the Brush mode changes from Gradient to Hatch. The function shown below will return the color values from the same Radio buttons that comes under these two set of radio groups which changes their name based on the brush mode:

//Sample 10: Get Color1 and Color2 from UI
private void Get_Col1_Col2(ref Color color1, ref Color color2)
{
    if (radhatCol1Blue.Checked == true)
        color1 = Color.Blue;
    else
        color1 = Color.Yellow;

    if (radHatCol2Green.Checked == true)
        color2 = Color.Green;
    else
        color2 = Color.Yellow;
}

7) The Inflate_Rect function written below will diminish the rectangular dimensions based on the current pen thickness. Note that the function takes the parameter as the reference type so the caller will expect the changes in the passed-in rectangular dimensions. So for we had looked at the some the helper functions written for the sample. Let us go the Hatch brush and filling techniques.

//Sample 11: Reduce rectangular dimension
private void Inflate_Rect(ref Rectangle rect)
{
    int inflate_to;
    int thickness;

    if (rad1.Checked == true)
        thickness = 1;
    else if (rad5.Checked == false)
        thickness = 3;
    else
        thickness = 5;

    inflate_to = thickness;

    rect.X = rect.X + inflate_to;
    rect.Y = rect.Y + inflate_to;
    rect.Width = rect.Width - inflate_to*2;
    rect.Height = rect.Height - inflate_to*2;
}

8) In the OnPaint handler after drawing the rectangle with the required Pen attributes, we fill the rectangle with the user selection of brush. Note that before making the Fill operation using the brush, the rectangle drawn using the Pen is inflated. You can create a solid brush by specifying the color. The graphics object supports lot of drawing functions with a Fill, say for example something like FillRectangle, FillEllipse etc. In the below code we make sure the Advanced brush option is not selected by the user and then create a SolidBrush by specifying the solid fill color. Once the brush is created it can be used with the Graphics object. In our case we used the solid brush with the FillRectangle function. Below is the code that creates and uses the Solid Brush:

Inflate_Rect(ref rect);
if (chkAdvBursh.Checked == false)
{
    //Sample 12.1: Create Solid Brush and Perform the Fill
    //A. Declaration
    Color brush_color ;
    Brush Solid_brush = null;
    //B. Create Solid Brush
    GetSolidBrushColor_FromUI(out brush_color);
    Solid_brush = new SolidBrush(brush_color);
    //C. Fill the Rectangle
    grp.FillRectangle(Solid_brush, rect);
}

9) Based on the Toggle Label, we create the Gradient Brush. To create gradient brush we need two colors as the gradient interpolates two colors in a linear way. Look at the previous picture for the gradient brush and in that the color interpolation is applied between blue and green in a horizontal way. In our example, we get both the colors required for the gradient effect by making a call to the function Get_Col1_Col2. Then we pass the from_color and to_color to the LinearGradientBrush contractor to create the Gradient_brush object. Once we have Gradient brush in hand we make a call to the function FillRectangle to get the Gradient effect. The code for this is shown below:

if (lblHatchGr.Text == "Gradient")
{
    //Sample 12.2: Create Gradient Brush and Perform the Fill
    //A. Declaration
    Color from_color= Color.White;
    Color to_color = Color.White;
    Brush Gradient_brush = null;
    //B. Create Gradient Brush
    Get_Col1_Col2(ref from_color, ref to_color);
    Gradient_brush = new LinearGradientBrush(rect, from_color, to_color,
        LinearGradientMode.Horizontal);
    //C. Fill the Rectangle
    grp.FillRectangle(Gradient_brush, rect);
}

In the above code, we asked the gradient to be applied horizontally by specifying the LinearGradientMode.Horizontal. The Gradient Modes are shown below:



10) In the else part of the Gradient Brush section we create the pattern brush to fill the rectangle. To see a pattern we should specify the Back Color and Fore Color when creating the pattern brush. After the having these colors (Note we used same function call Get_Col1_Col2), the user selected hatch pattern is stored in the style object. Refer msdn to know other hatch pattern as there are much more patterns available. All these information are passed to HatchBrush constructor to create the object Hatch_brush. Then as usual, this hatch brush is passed to the FillRectangle function of the Graphics object. The code is below which constructs the Pattern brush and uses that to fill the rectangle:

else
{
    //Sample 12.3: Create Hatch brush and perform the Fill
    //A. Declaration
    Color fore_color = Color.White;
    Color back_color = Color.White;
    Brush Hatch_brush = null;
    HatchStyle style;

    //B. Get Fore Color, Back Color. Also decide hatch style
    Get_Col1_Col2(ref fore_color, ref back_color);

    if (radHatTypeHorizontal.Checked == true)
        style = HatchStyle.Horizontal;
    else if (radHatTypeVerticle.Checked == true)
        style = HatchStyle.Vertical;
    else if (radHatTypeWave.Checked == true)
        style = HatchStyle.Wave;
    else
        style = HatchStyle.HorizontalBrick;

    //C. Create Pattern Brush
    Hatch_brush = new HatchBrush(style, fore_color, back_color);

    //D. Perform Drawing
    grp.FillRectangle(Hatch_brush, rect);
}

You can see the how the Brush works in the sample from the below shown video.


Video 3: Creating and using Brushes



Source Code: Download

Tuesday, August 13, 2013

[ MFC ] - Mapping Modes in VC++ Explained with SetWindowOrg, SetViewPortOrg

1. Introduction


MFC supports two kinds of coordinate systems. One is Device coordinate and the other one is Logical Co-Ordinate. In device coordinate, we specify everything in terms of pixels. In logical coordinate, we measure each unit in terms of Metric standard or British standard. How each unit maps to the logical measure is called the mapping. We can specify the mapping using the mapping modes.

In this article, I will walk you through the examples and explanation videos, which will help you in understanding the Mapping modes and performing the drawing using the device contexts. I will also help in understanding the ViewPort Origin and Window Origin.


2. Create SDI Application


The first step is creating the SDI Application without any document view Architecture support. Once the application is created, you can start your drawing using the OnPaint() handler. OK, Have a look at the below picture:



In the above depiction, the black screen is the desktop (Hided the Icons) and top left corner of the desktop (shown as P1) is the origin of the screen coordinate. The notepad application is displayed on top of the desktop(Screen) area. Point P2 specifies the origin of the notepad window or we can say that P2 is the origin of the window coordinate system. If there are three windows in the desktop area, then three such window coordinate exits (one for each window). The client area of the window is nothing but the working area of the window. In the case of the notepad, the actual working area is the portion of the window in which we actually type our textual content. Point P3 specifies the Origin of the client coordinate system. In all these coordinate systems we use the device coordinate meaning that the location and sizes are specified in terms of pixels.

We will talk more about the device coordinate in detail in some other article. But in the below piece of code, I will start with the client coordinate and then will move to mapping mode and logical coordinate based drawing.

CRect rct;
GetClientRect(&rct);

When you run the SDI application it looks like below (Resized):




The screen marked in blue is termed as client area of the window. The GetClientRect function will help in getting the rectangular marked as blue in the above depiction. We get four values left, top, right and bottom and this is also shown above. Look at the below video that debugs and examines value after calling GetClientRect() function.

3. Mapping Modes


The mapping modes are useful to perform the real world drawing. Say for example; let us say the software utility you are making is useful to perform an engineering drawing. When the drawing is printed out, you want to see the 10 mm line drawn in your monitor, measured exactly as 10 mm in the hard copy, taken from the printer. In this case, we need a way to represent how a single drawing unit measures to the real world measuring standards. MFC supports eight mapping modes which are shown in the below-specified picture:



For MM_TEXT mapping mode, the positive X moves from the default top left corner origin, to the right side. MM_ISOTROPIC and MM_ANISOTROPIC have a user-defined coordinate system. In MM_ISOTROPIC both x, y units are measured equally. But in the MM_ANISOTROPIC mode X and Y can have different units of measure. The above picture also shows for a given "mapping mode" how a single logical unit is measured. The MM_TEXT mapping mode is the default mapping mode used by MFC. Using the SetMapMode function of the underlying Device Context, you can pick any one of the mapping modes shown above.

4. Drawing a Line using mapping Modes


In the OnPaint handler, let us draw a line using MM_TEXT mode. Remember from the previous picture that each unit you specify to the drawing function represents a pixel. For an example, if the length of line 100 means, it is 100 pixels long as the mapping mode is MM_TEXT. Next thing we should remember is that the origin is in the upper-left corner of the window and positive Y goes down. So to see something when you draw, you should specify both x, y units in positive (Look at the picture for reference). OK, let us start drawing the line. Have a look at the below code:

//Sample 02: Draw Lines and see where the Origin is.
dc.MoveTo(0,0);
dc.LineTo(100,100);

In the above code, first, we moved the drawing pen to the Origin 0,0. Then asked to draw the line by specifying the end point as 100,100. When you run the Example you will see a line from origin 0,0 to the point at 100,100. This can be illustrated something like the below one:


For More explanation look at the video: 



What happens if I change the mapping mode from the default MM_TEXT to MM_LOMETRIC? The first thing one should be aware is that the Unit of measure changes from pixels to a millimeter. The second thing is that the Positive Y axis shifts its direction. Below is the Example that uses the MM_LOMETRIC as the mapping mode.

//Sample 03: Set New Mapping Mode
dc.SetMapMode(MM_LOMETRIC);
dc.MoveTo(0,0);
dc.LineTo(100,-100);
For More explanation look at the video: 


5.  Shifting the Origin using SetViewPortOrg


In the previous examples, we saw that how can we set the mapping modes on the device context. Also in the previous examples, the drawing origin is kept in the top left corner of the window, which is default origin. Device context has the capability of changing the origin from the default left corner using the SetViewPortOrg function call.
This function expects the new location in terms of pixel and shifts the drawing origin from top left corner to the new location. Have a look at the below code:

//Sample 01: Client Rectangle.
CRect rct;
GetClientRect(&rct);
//Sample 04.1: Shift the Origin to Screen Center
dc.SetViewportOrg(rct.right/2, rct.bottom/2);

In the OnPaint() handler, first the Origin is shifted from the top left corner to the center of the window. The rct is the CRect object, which has the Client Area dimension in device Co-Ordinate. So we specify the center of the client area in terms of a pixel to the SetWindowOrigin. Below is the picture which shows the shifted Origin:


The code in effect is shown in the above picture. The Red one is the origin before the shift and the blue one is the origin after the shift. Remember, again that we specified the new origin in terms of pixels. In the below code a blue pen is created and then a line is drawn. As there is no mapping mode set yet, the device context takes MM_TEXT as the mapping mode.

//Sample 04.2: Draw a blue Line MM_TEXT
CPen pen(PS_SOLID, 2, RGB(0,0,255));
CPen* OldPen = dc.SelectObject(&pen);
dc.MoveTo(0,0);
dc.LineTo(100,100);

After drawing the blue line, the red line is drawn in the MM_LOENGLISH mapping mode. At this stage, since you have gained a good idea of mapping modes, I am not going to explain that once again.

//Sample 04.2: Draw a Red Line using MM_LOENGLISH
dc.SetMapMode(MM_LOMETRIC);
CPen pen1(PS_SOLID, 10, RGB(255,0,0));
dc.SelectObject(&pen1);
dc.MoveTo(0,0);
dc.LineTo(100,100);
dc.SelectObject(OldPen);
Now running the entire code makes your drawing look like the one shown below:


For More explanation look at the video: 


6. Using the SetWindowOrg


At this stage, you know what the SetViewportOrg does. In a short summary again, the SetViewPortOrg sets the drawing origin by specifying the values in terms of pixels. The SetWindowOrg function set the given logical point as Lower Left Corner of the client Area Window.

Note the difference, View Port Origin is specified in terms of pixels and Window Origin is specified in terms of Logical units, which depends on the currently set mapping mode of the device context. Have a look at the below Example:

//Sample 05.1 Set the Mapping Mode and Viewport origin
dc.SetMapMode(MM_LOMETRIC);
dc.SetViewportOrg(rct.left, rct.bottom);

//Sample 05.2 Set this new location as top left of the client area
dc.SetWindowOrg(-100 , -100);

//Sample 05.3 Draw the Verticle and Horizontal line from the Origin (Viewport)
CPen pen1(PS_SOLID, 1, RGB(255,0,0));
CPen* OldPen = dc.SelectObject(&pen1);
dc.MoveTo(0,0);
dc.LineTo(0,500);
dc.MoveTo(0,0);
dc.LineTo(500,0);
dc.SelectObject(OldPen);

In this example first we set the mapping mode, as MM_LOMETRIC and I do not want to tell what it is. Then we shifted the drawing origin to lower left corner of the screen by specifying a location to be shifted as pixels. Then using the SetWindowOrg function, we specify the logical unit -100, -100 should be at the lower left corner of the window. Once this is done, we draw two lines using Red color Solid Pen. In those lines, one moves from the drawing origin(View Port Origin) to 500 unit in the positive, X direction and other one moves 500 units in positive, Y direction. Have a look at the below picture to understand this as it confuses most of MFC professionals:



For More explanation look at the video: 


Source Code : Download
Like this site? Tell it to your Firend :)