我正在尝试创建一个函数,该函数将在给定 Rectangle
结构的情况下创建一个三角形。我有以下代码:
public enum Direction {
Up,
Right,
Down,
Left
}
private void DrawTriangle(Graphics g, Rectangle r, Direction direction)
{
if (direction == Direction.Up) {
int half = r.Width / 2;
g.DrawLine(Pens.Black, r.X, r.Y + r.Height, r.X + Width, r.Y + r.Height); // base
g.DrawLine(Pens.Black, r.X, r.Y + r.Height, r.X + half, r.Y); // left side
g.DrawLine(Pens.Black, r.X + r.Width, r.Y + r.Height, r.X + half, r.Y); // right side
}
}
只要方向朝上,这个就可以工作。但是我有两个问题。首先,有没有一种方法可以始终绘制它,而只是分别将其旋转 0 度、90 度、180 度或 270 度,从而避免使用四个 if
语句?其次,如何用黑色填充三角形?
最佳答案
您可以绘制一个统一的三角形,然后使用矩阵变换对其进行旋转和缩放以适合矩形内部,但老实说,我认为这比定义每个点的工作量更大。
private void DrawTriangle(Graphics g, Rectangle rect, Direction direction)
{
int halfWidth = rect.Width / 2;
int halfHeight = rect.Height / 2;
Point p0 = Point.Empty;
Point p1 = Point.Empty;
Point p2 = Point.Empty;
switch (direction)
{
case Direction.Up:
p0 = new Point(rect.Left + halfWidth, rect.Top);
p1 = new Point(rect.Left, rect.Bottom);
p2 = new Point(rect.Right, rect.Bottom);
break;
case Direction.Down:
p0 = new Point(rect.Left + halfWidth, rect.Bottom);
p1 = new Point(rect.Left, rect.Top);
p2 = new Point(rect.Right, rect.Top);
break;
case Direction.Left:
p0 = new Point(rect.Left, rect.Top + halfHeight);
p1 = new Point(rect.Right, rect.Top);
p2 = new Point(rect.Right, rect.Bottom);
break;
case Direction.Right:
p0 = new Point(rect.Right, rect.Top + halfHeight);
p1 = new Point(rect.Left, rect.Bottom);
p2 = new Point(rect.Left, rect.Top);
break;
}
g.FillPolygon(Brushes.Black, new Point[] { p0, p1, p2 });
}
关于c# - 在给定矩形的情况下在 GDI+ 中绘制三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13537679/