Graphics |
Objectives |
Discussion |
Graphics
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.
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 Trail, Ball Without Trail, Stop).
Links & Help |