Graphics

Objectives


Discussion

Graphics

Back to top


Demonstration

In this demo we will show how to use the CreateGraphics method to draw on a form. 

1.  Open your Unit 8 project , add a new form, and make it the startup form.

2.  We will first add a background image to the form.  In the Properties Window select Background Image and select an image file.

3.  Now we will use CreateGraphics to draw a filled circle on the form.  We will use the MouseMove event for the form and draw a circle everytime the user moves the mouse.  In the code window, select BaseClassEvents in the upper left drop down box.  Select MouseMove in the right drop down box.  In this MouseMove event add the following code:

Me.CreateGraphics.FillEllipse(Brushes.Blue, _
e.X, e.Y, 20, 20)

4.  Run your program.  Hopefully when you move the mouse a circle is drawn on the form.  What would happen if you changed each "20" in the above statement?  If you are not sure then experiment.

5.  Now we will use CreateGraphics to draw text on the form.  We will also use the KeyPress event for the form and draw the letter of the key that the user presses.  In the KeyPress event for the form add the following code:

Me.CreateGraphics.FillRectangle( _
Brushes.Yellow, 0, 0, 50, 50)
Me.CreateGraphics.DrawString( _
e.KeyChar, New Font("arial", 20), _
Brushes.Black, 10, 10)

6.  Run your program and experiment.

7.  Now comment out the line

Me.CreateGraphics.FillRectangle( _
Brushes.Yellow, 0, 0, 50, 50)

8.  Run your program and experiment.

9.  Now add the following line of code just over the line that you commented out.

Me.Refresh()

10.  Run the program and experiment.  Notice that the refresh method clears the graphics.

Back to top
Exercises

1.  Create a form with a button on it.  When the user clicks the button the following should be drawn in a random location on the form: a circle, a filled rectangle, and a line connecting them.  Make the color of each different.  

2.  Create a form with a menu that has four items in a menu (Image, Ball With TrailBall Without Trail, Stop).

  1. When the user clicks Image, an image should be drawn on the form.  Use whatever image file that you want.  Each time the user clicks Image the image should be drawn in a slightly different location.  Do not use a picturebox.
  2. When the user clicks Ball With Trail, a filled-circle should move around the form leaving a trail (do not refresh).  Ideally you should get the ball to bounce around but you should at least get it to move.
  3. When the user clicks Ball Without Trail, a filled-circle should move around the form but NOT leave a trail (refresh).  Ideally you should get the ball to bounce around but you should at least get it to move.
  4. When the user clicks Stop the ball should stop moving.
Back to top
Links & Help
Back to top