5

这是我的代码。
我可以缩放图片框,但不能缩放。旋转鼠标滚轮时如何缩放到鼠标点?

变量是:-

private double m_dZoomscale = 1.0;    //THIS IS THE ZOOM SCALE TO WHICH EACH OBJECT 
                                      //ARE ZOOMED IN THE CANVAS  

public static double s_dScrollValue = .01;
                                      //scale factor value for mouse scroll zooming

油漆代码是:-

private void m_Picturebox_Canvas_Paint(object sender, PaintEventArgs e)
{
   Graphics g = e.Graphics;
   g.ScaleTransform((float)m_dZoomscale, (float)m_dZoomscale);
}

主要代码是:-

    protected override void OnMouseWheel(MouseEventArgs mea)
    {
        m_Picturebox_Canvas.Focus();
        if (m_Picturebox_Canvas.Focused == true)
        {
            if (mea.Delta > 0)
            {
                ZoomInScroll();
            }
            else if (mea.Delta < 0)
            {
                ZoomOutScroll();
            }
        }
    }

子功能如下:-

    //FUNCTION FOR MOUSE SCROL ZOOM-IN
    private void ZoomInScroll()
    {
        m_dZoomscale = m_dZoomscale + s_dScrollValue;
        m_Picturebox_Canvas.Invalidate();
    }

    //FUNCTION FOR MOUSE SCROL ZOOM-IN
    private void ZoomOutScroll()
    {
        m_dZoomscale = m_dZoomscale - s_dScrollValue;
        m_Picturebox_Canvas.Invalidate();
    }
4

1 回答 1

5

这是您实现此目的的方法(代码下方的描述):

变量

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

油漆代码

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

滚动事件代码

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);
    }
}

缩放功能

//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();
}

描述

首先,如您所见,我将您的两种缩放方法合并为一种方法:ZoomScroll 否则我们会重复很多逻辑......

那么这里做了什么?我想很明显,我们还需要对Graphics对象应用翻译。我们“累积”了应用于字段PictureBox的所有转换。Matrix

您成功地缩放了图像,但始终以原点(左上角PictureBox)作为缩放操作的局部中心 - 这就是Scale/的ScaleTransform工作原理!因此,为了在不同的点进行扩展,需要以下步骤:

  • 翻译世界,这样你想要缩放的点就是新的原点(例如你的光标在12|34,所以我们翻译-12|-34
  • 既然想要的地方是我们的新起点,规模
  • 将世界翻译回来,所以原点再次出现在您的光标下
于 2013-09-19T10:59:08.667 回答