我正在写一个WPF的小绘图应用程序。我使用DrawingVisual
类在Canvas
上渲染形状。
我想实现Canvas
控件的放大/缩小。
1)当我放大时,缩放焦点应该是鼠标的位置。
2)当我缩小时,缩放焦点应该是Canvas
的中心。
下面是我正在尝试的当前代码,但结果并不令人满意。
当我缩小时,所有形状都朝缩放后的中心位置移动,而不是向画布的实际中心位置移动。
因此,请指导我应该如何计算偏移X和Y,以便形状将移动到画布的中心。
double zoomFactor = 1.1;
double offsetX = 0;
double offsetY = 0;
protected override void OnMouseWheel(MouseWheelEventArgs e)
{
double absoluteMouseX;
double absoluteMouseY;
double centerX = this.ActualWidth / 2; //Canvas center X
double centerY = this.ActualHeight / 2; // Canvas center Y
Point relativeMouseToCanvas = e.GetPosition(this);
if (e.Delta > 0)
{
absoluteMouseX = relativeMouseToCanvas.X * this.Zoom + offsetX;
absoluteMouseY = relativeMouseToCanvas.Y * this.Zoom + offsetY;
this.Zoom *= zoomFactor;
offsetX = absoluteMouseX - relativeMouseToCanvas.X * this.Zoom;
offsetY = absoluteMouseY - relativeMouseToCanvas.Y * this.Zoom;
}
if (e.Delta < 0)
{
absoluteMouseX = centerX * this.Zoom + offsetX;
absoluteMouseY = centerY * this.Zoom + offsetY;
this.Zoom /= zoomFactor;
offsetX = absoluteMouseX - centerX * this.Zoom;
offsetY = absoluteMouseY - centerY * this.Zoom;
}
// Refresh/Repaint shapes on canvas
}
发布于 2014-02-13 12:55:53
在您的情况下,缩小将平移查看矩形的左上角。
这项计划清楚显示:
∆x = the difference of width between R1 and R2.
所以缩放x=(画布宽度)*缩放R2 -(画布宽度)*缩放R1
∆y也是如此:
∆y =(画布高度)*缩放R2 -(画布高度)*缩放R1
https://stackoverflow.com/questions/21746681
复制相似问题