Changes

Jump to: navigation, search

Drawing Graphics in C Sharp

2,696 bytes added, 16:36, 29 January 2008
no edit summary
[[Image:C_sharp_draw_line.jpg|Drawing a Line in C#]]
 
== Drawing Squares and Rectangles in C# ==
 
For the purposes of drawing rectangles and squares in C# the GraphicsObject provides the ''DrawRectangle()'' method. There are two two ways to use the ''DrawRectangle()'' method. One is to pass through a ''Rectangle'' object and Pen and the other is to create an instance of a Rectangle object and pass that through along with the Pen. We will begin by looking at drawing a rectangle without a pre-created rectangle object. The syntax for this is:
 
''graphicsobj''.DrawRectangle(''pen'', ''x'', ''y'', ''width'', ''height'');
 
The alternative is to pass through a Rectangle object in place of the co-ordinates and dimensions. The syntax for creating a Rectangle object in C# is as follows:
 
Rectangle ''rectangleObj'' = new Rectangle (''x'', ''y'', ''width'', ''height'');
 
Once a Rectangle object has been instantiated the syntax to call ''DrawRectangle()'' is as follows:
 
''graphicsobj''.DrawRectangle(''pen'', ''x'', ''y'', ''rectangleobj'');
 
The following example creates a Rectangle which is then used as an argument to ''DrawRectangle()'':
 
<pre>
private void Form1_Paint(object sender, PaintEventArgs e)
{
System.Drawing.Graphics graphicsObj;
 
graphicsObj = this.CreateGraphics();
 
Pen myPen = new Pen(System.Drawing.Color.Red, 5);
 
Rectangle myRectangle = new Rectangle(20, 20, 250, 200);
 
graphicsObj.DrawRectangle(myPen, myRectangle);
}
</pre>
 
When an application containing the above code is compiled and executed the following graphics will appear in the form:
 
[[Image:c_sharp_draw_rectangle.jpg|C Sharp Rectangle Drawing Example]]
 
If multiple rectangles of different shapes need to be drawn it it is not necessary to create a new Rectangle object for each call to the ''DrawRectangle();'' method. Instead the shape of an existing Rectangle object may be altered by calling the ''Inflate()'' method of the Rectangle class. This method accepts two arguments, the amount by which the width is to be changed and the amount by which the height is to be changed. If a dimension is to be left unchanged 0 should be passed through as the change value.
 
To reduce a dimension pass through the negative amount by which the dimension is to be changed:
 
<pre>
Rectangle myRectangle = new Rectangle(20, 20, 250, 200);
 
myRectangle.Inflate(10, -20); Increase width by 10. Reduce height my 20
</pre>
 
== Drawing Ellipses and Circles in C# ==
 
Ellipses and circles are drawn in C# using the '"DrawEllipse()'' method of the GraphicsObject class. The size of the shape to be drawn is defined by specifying a rectangle into which the shape must fit. As with

Navigation menu