I\'ve seen few questions about this problem, I tried every solution but none of them worked for my case. My code is working; this image shows what happens when I click on Draw b
This is not so hard, provided you know all the puzzle pieces.
Let's start with the obvious one:
Graphics
object to create zoomed graphics with ScaleTransform
.As I mentioned, this will include the widths of pens, font sizes and also any images you draw (though not the hatches of a HatchBrush
).
You also asked about keeping the drawing 'centered'. This is a non-obvious concept: Just what is the center of your drawing surface??
When zooming (just like rotating) you always need to know the center point of the zoom (or the rotation.) By default this is the origin (0,0)
. I chose the center of the Panel
. You may want to pick some other point..
Once you do you can move the origin of the graphics viewport to this point with TranslateTransform
.
Once you have achieved all this you almost certainly will want to allow scrolling.
To do so you have two options:
You can keep AutoScroll = false
and nest the canvas control inside another control, usually a Panel
, which has AutoScroll = true
; next make the canvas control big enough to always hold your drawing and you're done.
Or you can turn on AutoScroll
for the canvas control and also set a large enough AutoScrollMinSize
. If you then add the current scrolling position to the translation you are also done. Let's see this solution in action:
This is the code in the Paint
event:
Size sz = panel3.ClientSize;
Point center = new Point(sz.Width / 2, sz.Height / 2);
Graphics g = e.Graphics;
// center point for testing only!
g.DrawEllipse(Pens.Orange, center.X - 3, center.Y - 3, 6, 6);
// you determine the value of the zooming!
float zoom = (trackBar1.Value+1) / 3f;
// move the scrolled center to the origon
g.TranslateTransform(center.X + panel3.AutoScrollPosition.X,
center.Y + panel3.AutoScrollPosition.Y);
// scale the graphics
g.ScaleTransform(zoom, zoom);
// draw some stuff..
using(Pen pen = new Pen(Color.Yellow, 0.1f))
for (int i = -100; i < 100; i+= 10)
g.DrawEllipse(Pens.Yellow, i-22,i-22,44,44);
A few notes:
TrackBar
's Scroll
event is to trigger the Paint
event: panel3.Invalidate();
The only settings needed for the Panel
are
panel3.AutoScroll = true;
panel3.AutoScrollMinSize = new Size(500, 500); // use the size you want to allow!
However to avoid flicker it is highly recommended to use a DoubleBuffered
control, maybe a Panel
subclass like this:
class DrawPanel : Panel
{
public DrawPanel() { DoubleBuffered = true; }
}
Update: Instead of a Panel
, which is a Container
control and not really meant to draw onto you can use a Picturebox
or a Label
(with Autosize=false
); both have the DoubleBuffered
property turned on out of the box and support drawing better than Panels
do.
Graphics.ScaleTransform() is how you can zoom. Try using something like this inside your paint event handler:
e.Graphics.ScaleTransform(2.0F, 2.0F);