[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Let the user zoom on a picture in C#

[Let the user zoom on a picture in C#]

Important: This example does not handle new drawings correctly if you have scaled the image. Read this one to learn how it works and then see the new post Let the user zoom on a picture and draw 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.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.