给出一个矩形在GDI +中绘制一个三角形

时间:2012-11-24 02:18:06

标签: c# winforms gdi+

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

2 个答案:

答案 0 :(得分: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 });  
    }

答案 1 :(得分: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);