mrfangzheng

Hope and fear are useless. Be confident, and always be prepared for the worst.
  首页  :: 新随笔  :: 联系 :: 管理

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

Posted on 2008-07-09 22:46  mrfangzheng  阅读(734)  评论(0编辑  收藏  举报

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;
}