|Title||Let the user zoom and scroll a picture drawn by the program in Visual Basic .NET|
|Description||This example shows how to let the user zoom and scroll a picture drawn by the program in Visual Basic .NET.|
|Keywords||graphics, drawing, zoom, pan, scale, ScaleTransform, Visual Basic .NET, VB.NET|
The program contains a Panel with AutoScale = true. Inside the Panel is a PictureBox with SizeMode = AutoSize. The PictureBox contains a Bitmap that displays the drawing.
The basic idea is simple. When the user selects a scale, the program builds a Bitmap of the correct size. It makes a Graphics object to draw on the Bitmap and uses its ScaleTransform method to make it draw suitably scaled. The code then calls a drawing routine to make the drawing. The drawing routine uses the same code at all scales and the ScaleTransform call makes the result scale properly.
The following code shows the SetScale method that prepares the Bitmap, makes the Graphics object, calls that object's ScaleTransform method, and then calls DrawImage to do the drawing. The code is fairly self-explanatory.
' Set the scale and redraw.
Private Sub SetScale(ByVal picture_scale As Single)
' Set the scale.
PictureScale = picture_scale
' Make a Bitmap of the righ size.
Bm = New Bitmap( _
CInt(PictureScale * WorldWidth), _
CInt(PictureScale * WorldHeight))
' Make a Graphics object for the Bitmap.
' (If you need to use this later, you can give it
' class scope so you don't need to make a new one.)
Using gr As Graphics = Graphics.FromImage(Bm)
' Use a white background
' (so you can see where the picture is).
' Draw smoothly.
gr.SmoothingMode = _
' Draw the image.
' Display the result.
picCanvas.Image = Bm
' Draw the image in world coordinates.
Private Sub DrawImage(ByVal gr As Graphics)
Dim rect As Rectangle
rect = New Rectangle(10, 10, 80, 80)
rect = New Rectangle(40, 40, 20, 30)
rect = New Rectangle(25, 30, 50, 50)
gr.DrawArc(Pens.Red, rect, 20, 140)
rect = New Rectangle(25, 25, 15, 20)
rect = New Rectangle(30, 30, 10, 10)
rect = New Rectangle(60, 25, 15, 20)
rect = New Rectangle(65, 30, 10, 10)