简体   繁体   中英

Zooming about point when using a Viewbox inside a ZoomableCanvas?

Thanks to Kael Rowan, you can easily create a zoomable canvas in WPF . Sample project can be downloaded at the bottom of this blog entry .

Now, I need to modify this sample project to use its Viewbox feature. In MainWindow.xaml set the Viewbox , Stretch and ApplyTransform properties as follows:

<ZoomableCanvas ... Viewbox="0 0 400 400" Stretch="Fill" ApplyTransform="True" />

The problem

With this feature enabled, the zooming using the mouse wheel does not zoom about the mouse position. Instead, it seems to zoom around (0,0). This piece of code (in the mouse wheel handler) works without Viewbox :

// Adjust the offset to make the point under the mouse stay still.
var position = (Vector)e.GetPosition(MyListBox);
MyCanvas.Offset = (Point)((Vector)(MyCanvas.Offset + position) * x - position);

How can I get it working with a Viewbox ? This is driving me nuts! Math/WPF gurus out there, please help!

Try this code

protected override void OnMouseWheel(MouseWheelEventArgs e)
{ 
    var position = e.GetPosition(this.MyCanvas);

    var pre = this.MyCanvas.TransformToAncestor(this).Transform(position);

    var x = Math.Pow(2, e.Delta / 3.0 / Mouse.MouseWheelDeltaForOneLine);
    MyCanvas.Scale *= x;

    var cur = this.MyCanvas.TransformToAncestor(this).Transform(position);

    var offset = (cur - pre);

    this.MyCanvas.Offset += offset;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM