将偏移应用于缩放以保留特定点
本文关键字:保留 缩放 应用于 | 更新日期: 2023-09-27 18:28:25
我目前正在努力解决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来自相对于画布测量的鼠标事件,包括缩放。(当"比例"为2时,200的相对屏幕x坐标会给我400作为pt的值)
使用以下代码片段应用Transform(Scale):
mCanvasScale = new ScaleTransform();
mCanvas.LayoutTransform = mCanvasScale;
如何获得mTranslation的正确偏移量?
问候
Dennis
解决方案应该是
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;
}
}