GDI +基于鼠标指针放大/缩小

时间:2016-11-18 10:32:58

标签: c# gdi+

我希望以鼠标指针为中心放大/缩小矢量图形。 我的代码就是这样:

Matrix m_globalMatrix = new Matrix();
PointF m_scalePos;
float m_perZoom = 1.2f;
float m_zoom = 1f;
void ReCoord(){
    m_globalMatrix.Reset();
    m_globalMatrix.Translate(m_scalePos.X, m_scalePos.Y);
    m_globalMatrix.Scale(m_zoom, m_zoom); 
    m_globalMatrix.Translate(-m_scalePos.X, -m_scalePos.Y);
}
protected override void OnMouseWheel(MouseEventArgs e)
    {
        base.OnMouseWheel(e);
        //PointF temp;

        //temp = CoordTransform(e.Location);
        m_scalePos = (PointF)ScreenToCoord(e.Location);
        Console.WriteLine("m_scalePos:{0},Zoom:{1}", m_scalePos, m_zoom);

        if (e.Delta < 0)
        {
            m_zoom /= m_perZoom;
        }
        else
        {
            m_zoom *= m_perZoom;
        }

        ReCoord();

        Invalidate();
    }
 public CoordPoint ScreenToCoord(PointF screenPoint)
    {
        PointF[] points = new PointF[] { screenPoint };
        Matrix mx = m_globalMatrix.Clone();
        mx.TransformPoints(points);

        /*
        mx = m_coordMatrix.Clone();
        mx.TransformPoints(points);
        */
        return points[0];   
    /* I have struct like that:
    struct CoordPoint{
        float x,y;
        public static implicit operator CoordPoint(System.Drawing.PointF p)
        {
            return new CoordPoint(p.X, p.Y);
        }
    }
    */
    }

当m_zoom达到10或更高时,它将是异常的。 mouseWheel快速滚动,也会出现异常。 例如,当我在m_zoom&lt;之前在点(50,50)处慢慢滚动鼠标滚轮时10,它将打印m_scalePos:(50,50)。 异常不会打印m_scale:(50,50),甚至抛出OverflowException。

我的测试油漆代码:

protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        if (m_bmpBuffer == null)
        {
            ReSize(ClientRectangle.Width, ClientRectangle.Height);
        }
        m_graphics.FillRectangle(Brushes.Black, this.ClientRectangle);

        PointF[] pts = new PointF[]{
            new PointF(20,20),
            new PointF(80,80),
            new PointF(20,80),
            new PointF(80,20),
            new PointF(0,0)
        };
        for (int i = 0; i < pts.Length; i++)
        {
            pts[i] = (PointF)ScreenToCoord(pts[i]);
        }
        m_graphics.DrawLine(Pens.White, pts[0], pts[1]);
        m_graphics.DrawLine(Pens.White, pts[2], pts[3]);
        e.Graphics.DrawImage(m_bmpBuffer, 0, 0);
 }

我的目标是实现这张照片: enter image description here

0 个答案:

没有答案