Title: Zoom and scroll a picture drawn in C#
This program lets you zoom and scroll a picture drawn by the program. The program contains a Panel with AutoScale set to true. Inside the Panel is a PictureBox with SizeMode set to 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 method to make the drawing. The drawing method 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 to draw the picture.
// Set the scale and redraw.
private void SetScale(float picture_scale)
// Set the scale.
PictureScale = picture_scale;
// Make a Bitmap of the right size.
Bm = new Bitmap(
(int)(PictureScale * WorldWidth),
(int)(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 (Graphics gr = Graphics.FromImage(Bm))
// Use a white background
// (so you can see where the picture is).
// Draw smoothly.
gr.SmoothingMode = SmoothingMode.AntiAlias;
// Draw the image.
// Display the result.
picCanvas.Image = Bm;
This code creates a Bitmap of the correct scaled size and an associated Graphics object. It calls that object's ScaleTransform method to scale any drawing that follows and then calls the DrawImage method to do the drawing. This method finishes by displaying the Bitmap in the program's PictureBox.
The following code shows the DrawImage method.
// Draw the image in world coordinates.
private void DrawImage(Graphics gr)
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);
This method draws uses Graphics methods to draw a smiley face.
Notice that this code contains simple calls to drawing methods and doesn't know anything about the scale at which it is drawing.
Download the example to experiment with it and to see additional details.