Home and Learn: Intermediate Programming
Graphics Tutorials: For C# and VB NET Students
In the previous lesson, you saw how to draw a rectangle on your forms. In this lesson, you'll see how to draw an ellipse.
Ellipses are drawn in between the sides of rectangles. They are drawn like this:
Erase the sides of the rectangle and you're left with an ellipse.
So add another button to your form. Double click to get at the coding window. Set up a second Rectangle variable at the top of the code, just below rectangle1:
VB Net
Dim rectangle2 As Rectangle
C#
Rectangle rectangle1;
Add the following line to the button code in VB:
rectangle2 = New Rectangle(10, 10, 150, 100)
And this, in C#:
rectangle2 = new Rectangle(10, 10, 150, 100);
So the width of the rectangle will be 150 and the height 100. Now set up the Pen, just below the rectangle line:
VB
pen1 = New Pen(Color.DarkBlue, 2)
C#
pen1 = new Pen(Color.DarkBlue, 2);
Add a new drawOption, and then Invalidate command with these two lines (semicolons on the end in C#):
drawOptions = 3
Invalidate( )
Jump to your Paint event and add a new Case in VB:
Case 3
e.Graphics.DrawEllipse( pen1, rectangle2 )
And this in C#:
case 3:
e.Graphics.DrawEllipse( pen1, rectangle2 );
break;
This time, we're selecting DrawEllipse from the list of available Graphics Subroutines. In between the round brackets of DrawEllipse, you need a Pen, followed by the rectangle that you want to turn into an ellipse.
Run your programme and click your Ellipse button. Your form will then look like this one:
As you can see, though, the ellipse looks a little bit ragged. This is because of something called Aliasing. If you try to draw a curve onto a computer screen, it will get drawn in a grid. Like this:
The Alias part is all those little steps the jaggies, as they are known. Anti-Aliasing is filling in the steps to create a smooth curve. You can implement this in your code quite easily, with the SmoothingMode property. Add the following, just above your DrawEllipse line, but below Case 3 (again, semicolon on the end in C#):
e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
If you get any underlines, especially in C#, change the part after the equals sign to this:
System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
Your Select Case code should now look like this in VB Net:
And your switch statement should look like this in C#:
Run your programme and click your Ellipse button again. The ellipse should be a lot smoother:
Now try these two exercises. You should find them quite easy!
Fill your ellipse with a solid colour.
Draw a circle to the form, instead of an ellipse.
In the next lesson, we'll take a look at how to write VB Net and C# code to draw polygons.
Back to the Intermediate Programming Contents Page
Email us: enquiry at homeandlearn.co.uk