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

问题描述 投票:0回答:2

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

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)
    {


    }
c# draw system.drawing drawimage
2个回答
1
投票

使用单个函数进行绘图,并且为了降低复杂性和一致性,请使用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);
}

结果如下所示:

scr


-1
投票

你只需要创建一个带点的数组,然后配置填充的方式,然后绘制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,xMidyMid坐标。

    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);
    }
© www.soinside.com 2019 - 2024. All rights reserved.