矩形角度属性

本文关键字:属性 | 更新日期: 2023-09-27 18:35:47

是否可以在 C# 中设置矩形角度属性?

我试过这个:

Rectangle r = new Rectangle();
r.Width = 5;
r.Height = 130;
r.Fill = Brushes.Black;
r.RotateTransform.AngleProperty = 30; // Here is the problem
canvas1.Children.Add(r);

矩形角度属性

执行此操作的一种方法是将 RotateTransformation 应用于对象的 RenderTransform 属性:

r.RenderTransform = new RotateTransform(30);
RotateTransform rt1 = new RotateTransform();
rt1.Angle =30;
r.RenderTransform= rt1;

r.RenderTransform= new RotateTransform(30);

您需要在 Rectangle 为变化角度应用倾斜变换,请看以下内容: 如何:倾斜元素

您正在尝试设置依赖项属性的支持字段,该属性是只读的,不能以这种方式使用。

请改用正确的属性:

r.RenderTransform.Angle = 30;

另外,我猜一个新的矩形默认情况下没有旋转变换,所以你可能还需要创建一个新的实例:

r.RenderTransform= new RotateTransform();

昨天我解决了同样的问题。这是我在WinForms中使用的:

        GraphicsState graphicsState = graphics.Save();
        graphics.TranslateTransform(this.Anchor.Position.X, this.Anchor.Position.Y);
        graphics.RotateTransform(this.Anchor.Rotation);
        graphics.FillRectangle(new SolidBrush(this.Anchor.Color), this.Anchor.GetRelativeBoundingRectangle());
        graphics.Restore(graphicsState);

锚点是我创建的类。它源自我自己的矩形

internal class Rectangle
{
    public PointF Position { get; set; }
    public Color Color { get; set; }
    public SizeF Size { get; set; }
    public float Rotation { get; set; }
    public RectangleF GetRelativeBoundingRectangle()
    {            
        return new RectangleF(
            new PointF(-this.Size.Width / 2.0f, -this.Size.Height / 2.0f),
            this.Size);
    }
}

矩形的位置是矩形的中间(中心)点,而不是左角。

因此,回到第一个代码部分:

GraphicsState graphicsState = graphics.Save();

我保存图形设备的状态,以便我可以执行任何我想的操作,然后返回到原始视图。然后我将位置系统平移到矩形的中心并执行旋转

graphics.TranslateTransform(this.Anchor.Position.X, this.Anchor.Position.Y);
graphics.RotateTransform(this.Anchor.Rotation);

然后,我画矩形。根据您想要如何绘制矩形,这部分显然会有所不同。您可能会使用FillRectangle(就像我一样)或DrawRectangle,它只绘制边框:

graphics.FillRectangle(new SolidBrush(this.Anchor.Color), this.Anchor.GetRelativeBoundingRectangle());
最后,我

恢复了图形设备的原始状态,这取消了我仅用于绘制旋转矩形的平移和旋转

graphics.Restore(graphicsState);