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

14 篇文章 0 订阅
6 篇文章 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;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值