使用线条填充绘制的三角形

Fill a drawn triangle using lines

我需要生成一个新方法来填充下面代码中的三角形并单独调用它 有什么建议吗?

public void draw(Graphics g, Pen blackPen)
    {
        double xDiff, yDiff, xMid, yMid;

        xDiff = oppPt.X - keyPt.X;
        yDiff = oppPt.Y - keyPt.Y;
        xMid = (oppPt.X + keyPt.X) / 2;
        yMid = (oppPt.Y + keyPt.Y) / 2;

        // draw triangle
        g.DrawLine(blackPen, (int)keyPt.X, (int)keyPt.Y, (int)(xMid + yDiff / 2), (int)(yMid - xDiff / 2));
        g.DrawLine(blackPen, (int)(xMid + yDiff / 2), (int)(yMid - xDiff / 2), (int)oppPt.X, (int)oppPt.Y);
        g.DrawLine(blackPen, (int)keyPt.X, (int)keyPt.Y, oppPt.X, oppPt.Y);

    }

该方法应采用这两个参数

public void fillTriangle(Graphics g, Brush redBrush)
    {


    }

您只需要创建一个带点的数组,然后配置填充方式,然后绘制 FillPolygon 实体到 DrawPolygon 只是轮廓。

    public void draw(Pen blackPen)
    {
        Graphics draw = CreateGraphics();

        Point[] points = new Point[6];
        points[0].X = 0;
        points[0].Y = 0;
        points[1].X = 150;
        points[1].Y = 150;
        points[2].X = 0;
        points[2].Y = 150;

        using (SolidBrush fillvar = new SolidBrush(Color.FromArgb(100, Color.Yellow)))
        {
            draw.FillPolygon(fillvar, points.ToArray());
            draw.DrawPolygon(Pens.DarkBlue, points);
        }

    }

如果你想在某物内部绘制 FillPolygon,就像 PictureBox 一样,你只需将它分配给 Graphics draw

    Graphics draw = picturebox.CreateGraphics();

以上只是其工作原理的实际说明,请查看您的代码。缺少只是实现它的 xDiff、yiff、xMid、yMid 坐标。

    public void draw(Graphics g, Pen blackPen)
    {
        double xDiff, yDiff, xMid, yMid;

        Point[] points = new Point[6];
        points[0].X = 50;
        points[0].Y = 50;
        points[1].X = 150;
        points[1].Y = 150;
        points[2].X = 0;
        points[2].Y = 150;

        SolidBrush varbrush = new SolidBrush(Color.FromArgb(100, Color.Yellow));

        fillTriangle(g, varbrush, points);
    }

您必须将点传递给 fillTriangle 并在此方法中绘制它们。

    public void fillTriangle(Graphics g, Brush varbrush, Point[] points)
    {
        g.FillPolygon(varbrush, points.ToArray());
        g.DrawPolygon(Pens.Red, points);
    }

为绘图使用单一函数,为了降低复杂性和一致性,使用 GraphicsPath 对象。

void DrawGraphics(Graphics g, Pen pen, Brush brush)
{
    float xDiff=oppPt.X-keyPt.X;
    float yDiff=oppPt.Y-keyPt.Y;
    float xMid=(oppPt.X+keyPt.X)/2;
    float yMid=(oppPt.Y+keyPt.Y)/2;

    // Define path with the geometry information only
    var path = new GraphicsPath();
    path.AddLines(new PointF[] {
        keyPt,
        new PointF(xMid + yDiff/2, yMid-xDiff/2),
        oppPt,
    });
    path.CloseFigure();

    // Fill Triangle
    g.FillPath(brush, path);

    // Draw Triangle
    g.DrawPath(pen, path);
}

结果如下: