我试图在鼠标移动时旋转矩形。
我的代码:
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++;
答案 0 :(得分:4)
我猜你真正想要的是RenderTransform,其中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;
}