c# - 在给定矩形的情况下在 GDI+ 中绘制三角形

标签 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 语句?其次,如何用黑色填充三角形?

最佳答案

您可以绘制一个统一的三角形,然后使用矩阵变换对其进行旋转和缩放以适合矩形内部,但老实说,我认为这比定义每个点的工作量更大。

    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/

相关文章:

c# - 如何消除 RichTextBox 中段落之间的空格?

c# - 如何判断 Image.FromStream 是否完成

c# - 更改图像部分的颜色

c# - Asp.net MVC Controller 接受值或 null

c# - ***.tmp 不是有效的 win32 资源文件。如何解决 Visual Studio 上的这个奇怪错误?

c# - 如何在崩溃之前渲染debug.log消息

c# - 创建没有按钮且没有最小化和最大化按钮的自定义消息框

.net - EventArgs Cancel 如何在 FormClosing 事件中工作?

c# - 使窗体的背景透明

c# - 将 ICC 颜色配置文件应用于 C# (Dotnet) 中的图像