be sharp with c# (chapter 2, drawing figures)

Upload: pieter-blignaut

Post on 30-May-2018

212 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 Be sharp with C# (Chapter 2, Drawing Figures)

    1/7

    Chapter Two

    2Drawing FiguresAfter this chapter you shouldunderstand what the .NET framework is

    understand how to instantiate objects of the Graphics , Penand SolidBrush classes

    understand how to use the DrawLine() and other methods todraw a figure

    understand the concept of a constructor

    understand the coordinate system in the Windows environment

    understand the difference between declaration and instantiation

    Key concepts

    .NET

    Objects and classes

    Declaration and instantiation

    Constructor

    MethodScope

  • 8/14/2019 Be sharp with C# (Chapter 2, Drawing Figures)

    2/7

    Chapter 2 2 Drawing Figures

    The Graphics class

    Things to know

    The .NET framework is a library of classes and methods that programmers can include intheir programs. In other words, we don't have to do everything from scratch every timethat we need a special functionality. We can simply use the static methods of a class inthe .NET framework or we can define an object of an existing class and use the non-staticmethods.

    The .NET framework includes a class Graphics , which provides methods for drawing lines,curves, figures, images, and text on a control.

    Things to do

    Click File / New / Project Give a name to the project, Drawings .Browse to the folder where you want to save the project and ensure that the correct folderis in the Location box.Rename the file Form1.cs to frmDrawings.cs .Change the Text property of the form to Drawings .Put two buttons on the form, namely Draw and Close . Give it appropriate names.Put a panel on the form and name it pnlDrawings . Change the BackColor property of thepanel to White .Ensure that all controls are neatly aligned.Write the appropriate code for the Close button.

    Enter the following line of code directly underneath the header of the partial class for theform. This line declares an instance (object), grphPanel , of the Graphics class. Notethat the object is not yet instantiated, it has only been declared.

    Graphics grphPanel;

  • 8/14/2019 Be sharp with C# (Chapter 2, Drawing Figures)

    3/7

    Chapter 2 3 Drawing Figures

    Enter the following line of code in the form's constructor method, frmDrawings() , justafter the call to the InitializeComponent() method. This line instantiates the object,grphPanel , as the graphics for the panel, pnlDrawings .

    grphPanel = pnlDrawings.CreateGraphics();

    Enter the following two lines of code in the Click() event handler of the Draw button.

    Pen penBlack = new Pen ( Color .Black, 2);grphPanel.DrawLine(penBlack, 0, 0, 50, 50);

    The first line declares an instance (object), penBlack , of the Pen class. The Pen class hasbeen defined in the .NET framework. An instance of the class describes how a shape (lineor rectangle, etc.) is outlined. In other words, it describes the colour and thickness of thelines. You can play around with other values for the two parameters in the constructormethod above.

    The second line draws a line using the pen that has just been declared from the (0,0)

    coordinate to the (50,50) coordinate on the panel.

    Here is a challenge for you: Make use of the panel's Width and Height properties andchange the code above so that a cross is drawn across the entire panel as in the screenprint below. Draw the two lines in two different colours.

    Things to know and understand

    Inspect the code below and then make sure that you understand the comments thereafter:

  • 8/14/2019 Be sharp with C# (Chapter 2, Drawing Figures)

    4/7

    Chapter 2 4 Drawing Figures

    The curly braces and indents in the code serve to indicate the scope of particular pieces of code (indicated with boxes). Make sure that you understand that one level of scope fitscompletely inside another.

    You should understand the difference between a declaration and an instantiation . Adeclaration gives a name to an object of a specific class although it does not necessarilyexist. The object comes to life only when it is instantiated. Before then, it does not exist,even if it might have a name. (Much like a mother decides on a name for her child beforehe/she is born.)

    The scope of an object is determined by the place where it is declared and not where it isinstantiated. The object grphPanel has a scope that makes it available to all methods inthe code while the object penBlack has a scope that limits it to the method btnDraw_Click . This means that penBlack is not available to any other method.

    Besides limited scope, a variable that is local to a method also has limited life span . It onlyexists as long as the method is executing. In other words, the next time that btnDraw is

    clicked a new penBlack will be instantiated.A constructor is a special kind of method. It is a method as any other in that itencapsulates a piece of code that does something, but it differs in the sense that it isexecuted when an object is instantiated. This means that for every object, its constructoris executed exactly once. It is the very first method that is called after an object has beeninstantiated; it is always called when the object is instantiated and it is never called afterthat again.

    Furthermore, a constructor has the same name as the class that it belongs to. In theexample above, the method frmDrawings() is the constructor of the form frmDrawings .Therefore, the method frmDrawings() is executed when you press F5 to run theapplication because it is then that the form is instantiated.

    To summarise: In the example above, we have three methods, namely the constructor of the form and two event handlers that handle the Click events of the two buttonsrespectively.

  • 8/14/2019 Be sharp with C# (Chapter 2, Drawing Figures)

    5/7

    Chapter 2 5 Drawing Figures

    In this example, the object grphPanel is declared and instantiated in two different lines of code. The declaration is done so that the scope of grphPanel will allow it to be available toall methods in the form. The instantiation is done so that grphPanel will be available assoon as the form is created.

    The object penBlack is declared and instantiated in one single line.

    Pen penBlack = new Pen ( Color .Black, 2);

    The part Pen penBlack does the declaration and the part penBlack = newPen ( Color .Black, 2) does the instantiation.

    Make sure that you understand that the first occurrence to the word Pen refers to theclass of the new object while the second occurrence refers to the constructor of the class

    (remember that a class and its constructor has the same name). The constructor is amethod as any other and may take parameters (values between brackets). In this case,the first parameter indicates the colour of the new pen and the second parameter thethickness thereof (in pixels).

    The coordinate system in the Windows environment differs somewhat from the coordinatesystem that we are used to in Mathematics. In Windows, the origin (0,0) is in the top left-hand corner (not in the bottom-left as in Mathematics). The x-axis grows to the right andthe y-axis grows downward (not upward as in Mathematics).

    The second line in the Click() event handler of the Draw button draws a line on thepanel.

    grphPanel.DrawLine(penBlack, 0, 0, 50, 50);

    This line refers to two objects, namely the Graphics object, grphPanel , and the Penobject, penBlack . The Graphics object calls a method, DrawLine() , which is part of theGraphics class as it is defined in the .NET framework.

    The DrawLine() method takes five parameters. The first parameter defines the pen thatmust be used to draw the line, thereby implicitly defining the colour and thickness of theline. The next two parameters indicate the coordinates of the starting point and the lasttwo parameters the coordinates of the end point of the line.

    Therefore, in plain English the line above means: Draw a line from (0,0) to (50,50) on thepanel. Use a black pen with thickness 2 pixels.

    Class

    Object name

    Instantiate new object

    Constructor

    Parameters

    (0,0)x

    y (50,50)

    Object Method call Parameters

  • 8/14/2019 Be sharp with C# (Chapter 2, Drawing Figures)

    6/7

    Chapter 2 6 Drawing Figures

    Keywords

    You should make sure that you know what each of these items mean or where they are used.

    BraceColorConstructorCoordinate systemCreateGraphics()DeclareDrawEllipse()DrawLine()DrawRectangle()Event handler

    FillEllipse()GraphicsHeightIndentInstantiateLife spanMethod MouseMove().NET frameworknew

    Non-static methodObjectPanelPenPixelScopeSolidBrushStatic method Width

    Key:

    Concepts : NormalClasses and Controls : Green, e.g. ColorProperties : Bold, e.g. HeightMethods : Bold with brackets, e.g. FillEllipse()Reserved words : Blue, e.g. new

    Exercises

    1. Develop a program that will draw a square on the panel through four different calls of theDrawLine() method.

    Hint: Add a label somewhere on the form, lblCoordinates , and enter the following codefor the MouseMove event of the panel. You might not understand (yet) how it works, butit could help you.

    private void pnlDrawings_MouseMove( object sender, MouseEventArgs e){

    lblCoordinates.Text = "(" + e.X.ToString() + ", " + e.Y.ToString() + ")" ;}

    2. Develop a program that will draw a square on the panel by calling the DrawRectangle()method. Use Intellisense to inspect the purpose of each one of the parameters. Makesure that you understand that the fourth and fifth parameters refer to the width andheight of the rectangle.

    3. Develop a program that will draw a circle on the panel by calling the DrawEllipse()method.

    Hint: You may place various buttons on the form, each drawing a different figure. Youcan clear the previous drawings with

    grphPanel.Clear( Color .White);

  • 8/14/2019 Be sharp with C# (Chapter 2, Drawing Figures)

    7/7

    Chapter 2 7 Drawing Figures

    4. Develop a program to draw this figure on the panel.

    5. Change the program in number 4. Change the colour of the arms and legs. Use themethod FillEllipse() to draw solid blue eyes. The following two lines of code mighthelp:

    SolidBrush brshBlue = new SolidBrush ( Color .Blue);grphPanel.FillEllipse(brshBlue, 110, 25, 5, 5);

    Use IntelliSense to discover the colours that are available.

    Be creative and add additional elements such as hands and feet, a hat and a cigar, etc.