我试图在鼠标移动时旋转一个矩形。
我的代码:
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++;