Title: Let the user zoom on a picture in C#
The example Provide autosave in C# explains how to make a program that lets the user draw lines in different colors and styles. That program lets the user undo and redo, save and load drawings, and autosaves so it can reload a drawing if it crashes.
This example adds the ability to zoom in and out on the drawing.
The program uses a PictureBox inside a Panel control. The PictureBox has a fixed size and doesn't resize its image. The Panel has AutoScroll = True so it displays scrollbars if the PictureBox is too big to fit.
When you select a scale from the toolbar's ComboBox, the program calls the following SetScale method to set the selected scale.
// Set the scale and redraw.
private void SetScale(float picture_scale)
{
// Set the scale.
PictureScale = picture_scale;
// Resize the PictureBox.
picCanvas.ClientSize = new Size(
(int)(WorldWidth * PictureScale),
(int)(WorldHeight * PictureScale));
// Redraw.
picCanvas.Refresh();
}
This method saves the new scale in variable PictureScale. It then resizes the PictureBox for that scale and refreshes it to make it redraw the picture. When the PictureBox resizes, the Panel control automatically displays scrollbars if needed.
The following code shows how the PictureBox redraws the picture.
// Draw the picture.
private void picCanvas_Paint(object sender, PaintEventArgs e)
{
// Ready.
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.Clear(Color.White);
// Scale.
e.Graphics.ScaleTransform(PictureScale, PictureScale);
// Draw.
foreach (Polyline polyline in Polylines)
{
polyline.Draw(e.Graphics);
}
}
This code sets the Graphics object's SmoothingMode and clears the picture with white. Next the method uses the Graphics object's ScaleTransform method to scale future drawing by the current scale factor. The method finishes by looping through the current Polyline objects and calling their Draw methods.
Download the example to experiment with it and to see additional details.
|