0

我目前正在努力使用 WPF 画布和缩放。我希望能够围绕特定点缩放画布(缩放后给定点应保持在同一屏幕位置)。

缩放是通过简单的ScaleTransform完成的。平移存储在Point对象中,并应用于画布中的所有形状。这意味着我必须在应用缩放后偏移所有形状(修改平移点)。为了简单起见,这里有一个简化的代码

class CanvasManager
{
    Point mTranslation; // holds the translation
    Canvas mCanvas;
    ScaleTransform mCanvasScale; // linked to mCanvas

    // Constructor omitted

    public void Scale(double factor, Point pt)
    {
        // retrieve the previous scaling factor
        double oldfactor = mCanvasScale.ScaleX;
        //apply the new factor
        mCanvasScale.ScaleX = factor;
        mCanvasScale.ScaleY = factor;
        // now offset so Point pt gets back at its original position
        mTranslation.X += ???;
        mTranslation.Y += ???;
    }
}

pt来自相对于画布测量的鼠标事件,包括缩放。(当 Scale 为 2 时,相对屏幕 x 坐标 200 给我 400 作为pt的值)
Transform (Scale) 应用以下代码片段:

mCanvasScale = new ScaleTransform();
mCanvas.LayoutTransform = mCanvasScale;

如何获得 mTranslation 的正确偏移量?

最好的问候
丹尼斯

4

1 回答 1

1

解决方案应该是

class CanvasManager
{
    Point mTranslation; // holds the translation
    Canvas mCanvas;
    ScaleTransform mCanvasScale; // linked to mCanvas

    // Constructor omitted

    public void Scale(double factor, Point pt)
    {
        // retrieve the previous scaling factor
        double oldfactor = mCanvasScale.ScaleX;
        //apply the new factor
        mCanvasScale.ScaleX = factor;
        mCanvasScale.ScaleY = factor;
        // now offset so Point pt gets back at its original position
        mTranslation.X -= ( (pt.X * factor) - (pt.X * oldfactor) ) / factor;
        mTranslation.Y -= ( (pt.Y * factor) - (pt.Y * oldfactor) ) / factor;
    }
}
于 2013-08-20T18:20:06.407 回答