wpf 旋转一个矩形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16224830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rotate a rectangle
提问by Finchsize
I tried to rotate a rectangle when mouse is moving.
My code:
我试图在鼠标移动时旋转一个矩形。
我的代码:
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++;
}
I want to make rotation by center of my rectangle, but it making it in another way. This lines:
我想通过矩形的中心旋转,但它以另一种方式旋转。这行:
rotation.CenterX = Canvas.GetLeft(rect) + rect.Width/2;
rotation.CenterY = Canvas.GetTop(rect) + rect.Height/2;
dont change anything at all. Do you know why ?
不要改变任何东西。你知道为什么吗 ?
I found a solution in another post in this forum, so my solutionfor this is:
我在本论坛的另一篇文章中找到了解决方案,因此我的解决方案是:
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++;
回答by Clemens
I guess what you actually want is a RenderTransformwith a RenderTransformOriginat the center of the Rectangle:
我猜你真正想要的是一个RenderTransform,在 Rectangle 的中心有一个RenderTransformOrigin:
<Rectangle Fill="Orange" Width="100" Height="100" RenderTransformOrigin="0.5,0.5">
<Rectangle.RenderTransform>
<RotateTransform x:Name="rotateTransform"/>
</Rectangle.RenderTransform>
</Rectangle>
Write the MouseMove handler like this:
像这样编写 MouseMove 处理程序:
double angle = 0;
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
rotateTransform.Angle = angle; // yes, Angle is a double
angle += 1;
}

