How to zoom at a point in picturebox

帅比萌擦擦* 提交于 2019-12-01 19:01:26

Here is how you achieve this (description below code):

Variables

// this tracks the transformation applied to the PictureBox's Graphics
private Matrix transform = new Matrix();      
public static double s_dScrollValue = 1.01; // zoom factor

Paint code

private void m_Picturebox_Canvas_Paint(object sender, PaintEventArgs e)
{
   Graphics g = e.Graphics;
   g.Transform = transform;
}

Scroll-Event code

protected override void OnMouseWheel(MouseEventArgs mea)
{
    m_Picturebox_Canvas.Focus();
    if (m_Picturebox_Canvas.Focused == true && mea.Delta != 0)
    {
        ZoomScroll(mea.Location, mea.Delta > 0);
    }
}

Zoom function

//FUNCTION FOR MOUSE SCROL ZOOM-IN
private void ZoomScroll(Point location, bool zoomIn)
{
    // make zoom-point (cursor location) our origin
    transform.Translate(-location.X, -location.Y);

    // perform zoom (at origin)
    if(zoomIn)
        transform.Scale(s_dScrollValue, s_dScrollValue);
    else
        transform.Scale(1 / s_dScrollValue, 1 / s_dScrollValue);

    // translate origin back to cursor
    transform.Translate(location.X, location.Y);

    m_Picturebox_Canvas.Invalidate();
}

Description

First of all, as you can see I combined your two zoom methods to one method: ZoomScroll Otherwise we would duplicate a lot of logic...

So what is done here? I guess it is clear that we need to also apply a translation to the Graphics object. We "accumulate" all transformation applied to the PictureBox in a Matrix field.

You successfully scaled your image, but always with the origin (upper-left corner of the PictureBox) as the locical center of your scaling-operation - that is just how Scale/ScaleTransform works! So in order to scale at a different point the following steps are needed:

  • translate the world, so that the point you want to scale at is the new origin (e.g. your cursor is at 12|34, so we translate by -12|-34)
  • now that the desired spot is our new origin, scale
  • translate the world back, so the original point ends up under your cursor again
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!