gpt4 book ai didi

c# - 旋转一个矩形

转载 作者:行者123 更新时间:2023-11-30 20:58:19 26 4
gpt4 key购买 nike

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

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++;

最佳答案

我猜你真正想要的是 RenderTransformRenderTransformOrigin在矩形的中心:

<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;
}

关于c# - 旋转一个矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16224830/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com