BLOG.CSHARPHELPER.COM: Let the user zoom and scroll a picture drawn by the program in C#
Let the user zoom and scroll a picture drawn by the program in C#
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 void SetScale(float picture_scale) { // Set the scale. PictureScale = picture_scale;
// Make a Bitmap of the righ 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). gr.Clear(Color.White);
The following code shows the DrawImage method that draws the smiley face.
// Draw the image in world coordinates. private void DrawImage(Graphics gr) { Rectangle rect;
rect = new Rectangle(10, 10, 80, 80); gr.FillEllipse(Brushes.LightGreen, rect); gr.DrawEllipse(Pens.Green, rect);
rect = new Rectangle(40, 40, 20, 30); gr.FillEllipse(Brushes.LightBlue, rect); gr.DrawEllipse(Pens.Blue, rect);
rect = new Rectangle(25, 30, 50, 50); gr.DrawArc(Pens.Red, rect, 20, 140);
rect = new Rectangle(25, 25, 15, 20); gr.FillEllipse(Brushes.White, rect); gr.DrawEllipse(Pens.Black, rect); rect = new Rectangle(30, 30, 10, 10); gr.FillEllipse(Brushes.Black, rect);
rect = new Rectangle(60, 25, 15, 20); gr.FillEllipse(Brushes.White, rect); gr.DrawEllipse(Pens.Black, rect); rect = new Rectangle(65, 30, 10, 10); gr.FillEllipse(Brushes.Black, rect); }
Notice that this code contains simple calls to drawing methods and doesn't know anything about the scale at which it is drawing.
Comments