WPF : 以鼠标指针为中心缩放

XMAL:

<Canvas
    x:Name="mCanvas"
    MouseWheel="mCanvas_MouseWheel"
    Background="Wheat"
>
<Canvas.RenderTransform>
    <TransformGroup>
        <ScaleTransform x:Name="mScaleTf" ScaleX="1.0" CenterX="0"></ScaleTransform>        
        <TranslateTransform x:Name="mTranslateTf" X="10" Y="20"></TranslateTransform>
    </TransformGroup>
</Canvas.RenderTransform>
</Canvas>

------------------------------------------------------------------------------------------------------

Code:

private void mCanvas_MouseWheel(object sender, MouseWheelEventArgs e)
{

           Point zoomCenter = e.GetPosition(this.mCanvas);//参数必须是this.mCanvas, e.GetPosition和RenderTransform有关?

            //或者:
            //Point screenPos = e.GetPosition(this);
            //Point zoomCenter = this.mCanvas.RenderTransform.Inverse.Transform(screenPos);

 

            Point pt = this.mCanvas.RenderTransform.Inverse.Transform(zoomCenter);
            this.mTranslateTf.X = (zoomCenter.X - pt.X) * this.mScaleTf.ScaleX ;
            this.mTranslateTf.Y = (zoomCenter.Y - pt.Y) * this.mScaleTf.ScaleY;
            this.mScaleTf.CenterX = zoomCenter.X;
            this.mScaleTf.CenterY = zoomCenter.Y;
            this.mScaleTf.ScaleX += e.Delta / 1000.0;
            this.mScaleTf.ScaleY += e.Delta / 1000.0;

            Console.WriteLine("MouseWheel : " + zoomCenter.ToString());

}

或者

private void mCanvas_MouseWheel(object sender, MouseWheelEventArgs e)
{
    Point mousePos = e.GetPosition(this);

    //oldCenter : untransformed and transformed
    Point untransformedOldCenter = new Point(this.mScaleTf.CenterX, this.mScaleTf.CenterY);
    Point transformedOldCenter = this.mScaleTf.Transform(untransformedOldCenter);

    //newCenter : untransformed and transformed
    Point untransformedNewCenter = this.mCanvas.RenderTransform.Inverse.Transform(mousePos);
    Point transformedNewCenter = mousePos;

    double adjustX = transformedNewCenter.X - transformedOldCenter.X - untransformedNewCenter.X + untransformedOldCenter.X;

    //update transforms
    this.mTranslateTf.X = adjustX;
    this.mScaleTf.CenterX = untransformedNewCenter.X;
    this.mScaleTf.ScaleX += 0.1;
}

你可能感兴趣的:(WPF)