是否可以在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);
答案 0 :(得分:5)
执行此操作的一种方法是将RotateTransformation应用于对象的RenderTransform
属性:
r.RenderTransform = new RotateTransform(30);
答案 1 :(得分:2)
RotateTransform rt1 = new RotateTransform();
rt1.Angle =30;
r.RenderTransform= rt1;
OR
r.RenderTransform= new RotateTransform(30);
答案 2 :(得分:1)
您正在尝试设置依赖项属性的支持字段,该字段是只读的,并不打算以这种方式使用。
改为使用正确的属性:
r.RenderTransform.Angle = 30;
另外,我猜测一个新的Rectangle默认情况下没有RotateTransform,所以你可能也需要创建一个新的实例:
r.RenderTransform= new RotateTransform();
答案 3 :(得分:1)
你需要对 矩形中的变化角度应用倾斜变换,请看:How to: Skew an Element
答案 4 :(得分:1)
昨天我解决了同样的问题。这就是我在 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);
Anchor是我创建的一个类。它来自我自己的矩形
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);