2

我试图在鼠标移动时旋转一个矩形。
我的代码:

private int i = 0;

private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
    RotateTransform rotation = new RotateTransform();
    rotation.Angle = i;
    rotation.CenterX = Canvas.GetLeft(rect) + rect.Width/2;
    rotation.CenterY = Canvas.GetTop(rect) + rect.Height/2;
    rect.LayoutTransform = rotation;
    i++;         
}

我想按矩形的中心进行旋转,但它以另一种方式进行。这行:

rotation.CenterX = Canvas.GetLeft(rect) + rect.Width/2;
rotation.CenterY = Canvas.GetTop(rect) + rect.Height/2;

不要改变任何东西。你知道为什么吗 ?

我在这个论坛的另一篇文章中找到了解决方案,所以我的解决方案是:

            double left = Canvas.GetLeft(rect);
            double top = Canvas.GetTop(rect);

            Canvas.SetLeft(rect, 0);
            Canvas.SetTop(rect, 0);

            RotateTransform rotation = new RotateTransform();
            rotation.Angle = i;
            rotation.CenterX = rect.Width/2;
            rotation.CenterY = rect.Height/2;
            rect.RenderTransform = rotation;

            Canvas.SetLeft(rect, left);
            Canvas.SetTop(rect, top);
            i++;  
4

1 回答 1

5

我猜你真正想要的是一个RenderTransform,在 Rectangle 的中心有一个RenderTransformOrigin :

<Rectangle Fill="Orange" Width="100" Height="100" RenderTransformOrigin="0.5,0.5">
    <Rectangle.RenderTransform>
        <RotateTransform x:Name="rotateTransform"/>
    </Rectangle.RenderTransform>
</Rectangle>

像这样编写 MouseMove 处理程序:

double angle = 0;

private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
    rotateTransform.Angle = angle; // yes, Angle is a double
    angle += 1;
}
于 2013-04-25T21:47:54.633 回答