简体   繁体   中英

C# winforms - How to use the current mouse position as the zoom center to zoom the entire picturebox including the drawing content?

Problem - when I didn't do the zooming, I could draw some graphics by getting the clicked position of the mouse. After I have zoomed with the mouse wheel, the position where I clicked the mouse was deviated from the position displayed on the canvas.

I seem to only zoom the drawing objects in the Paint event, the picturebox is not zoomed. when I have zoomed, and I checked the coordinates of the upper left corner of the picturebox, it is still (0, 0). I don't think the coordinates of the upper left corner should be (0, 0) after scaling.

My zoom function code is down below:

private void picturebox_MouseWheel(object sender, MouseEventArgs e)
{
    if(e.Delta < 0)
    {
         _zoom += 0.1f;
         _offsetX = e.X * (1f - _zoom);
         _offsetY = e.Y * (1f - _zoom);
    }
    else
    {
         if (_zoom <= 1f)
         {
              return;
         }
         _zoom -= 0.1f;
         _offsetX = e.X * (1f - _zoom);
         _offsetY = e.Y * (1f - _zoom);
     }
     picturebox.Invalidate();
}

private void picturebox_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.TranslateTransform(_offsetX, _offsetY);
    e.Graphics.ScaleTransform(_zoom, _zoom);
    e.Graphics.DrawLine(Pens.Black, 10, 10, 30, 30);
    e.Graphics.DrawRectangle(Pens.Black, 10, 10, 30, 30);
}

[Edit - add a Form properties screenshot] 在此处输入图像描述

I would appreciate any help, it would be better if your answer could be more detailed.

Based on the referred problem , to scale and offset the view to the mouse wheel position:

private float zoom = 1f;
private PointF wheelPoint;

private void picturebox_MouseWheel(object sender, MouseEventArgs e)
{
    zoom += e.Delta < 0 ? -.1f : .1f;
    zoom = Math.Max(.1f, Math.Min(10, zoom));            
    wheelPoint = new PointF(e.X * (zoom - 1f), e.Y * (zoom - 1f));
    picturebox.Invalidate();
}

Offset and scale before drawing your shapes:

private void picturebox_Paint(object sender, PaintEventArgs e)
{
    var g = e.Graphics;

    g.TranslateTransform(-wheelPoint.X, -wheelPoint.Y);
    g.ScaleTransform(zoom, zoom);

    // Draw....
}

SO73133298

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM