4

我正在尝试创建一个函数,该函数将在给定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语句?其次,如何用黑色填充三角形?

4

2 回答 2

3

您可以绘制一个统一的三角形,然后使用矩阵变换对其进行旋转和缩放以适应矩形,但老实说,我认为这不仅仅是定义每个点需要做更多的工作。

    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 });  
    }
于 2012-11-25T05:40:25.803 回答
1

Graphics.TransformMatrix.Rotate解决旋转部分。Graphics.FillPolygon用于填充三角形。

从示例到以下相应方法的近似未编译代码:

// Create a matrix and rotate it 45 degrees.
Matrix myMatrix = new Matrix();
myMatrix.Rotate(45, MatrixOrder.Append);
graphics.Transform = myMatrix;
graphics.FillPolygon(new SolidBrush(Color.Blue), points);
于 2012-11-24T06:54:40.357 回答