Drawing in Visual Basic

We would like to draw a circle whenever the user clicks the mouse on the form. Before we can draw we need something to draw with, a pen, and something to draw on. We can't actually draw on the form, but rather the graphics area of the form.

Start a new Windows application and save it as Drawing. Double click on the form, then select the click event for the form and write the code as shown below:

Public Class Form1
Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
Dim MyPen As New Pen(Color.Black, 3) 'Black, width of 3
Me.CreateGraphics.DrawEllipse(MyPen, e.X, e.Y, 30, 30)
'width and height of 30 at position of mouse
End Sub
End Class

Objects

The types integer, double, and char are called primitive types. They hold a single value. Variables declared as primitive types can be given values and used in expressions but they can't do anything.

Pen is a class. A class has methods and properties. (Form is also a class.) We declare MyPen to be an instance of the Pen class.  MyPen is called an object. An object has all of the methods and properties of the class. We need a pen or brush in order to draw things.

Notice that the declaration of MyPen uses the word New. New must be used when you declare an instance of a class. The declaration of a pen allows you to assign values to the properties Color and Width. We have selected Black for the initial value of the color and 3 as the width. We can change these properties later if we want.

an ellipse
A form is also an object. Forms have lots of methods. The statement Me.CreateGraphics creates a graphics object. Graphics object also have lots of methods, we have chosen to draw an ellipse. The ellipse has 4 different formats. The one we are using requires 5 arguments: a pen, the x and y values to begin drawing at, the width and height of the ellipse. If the width and height are the same, we get a circle. If you look closely when you click, you will notice that the point you click is the top left corner of the rectangle that bounds the circle.
Experiment: How would you make the center of the circle at the point you clicked?


NEXT: The Brush