0
我正在WPF中編寫一個小型繪圖應用程序。我正在使用DrawingVisual
類來呈現Canvas
上的形狀。放大鼠標位置並在畫布中心縮小(不使用ScaleTransform)
我想爲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
}