Protium
Protium

Reputation: 213

draw an equilateral triangle C#

I have tried to adapt some code I came across to draw an equilateral triangle in c#

 public void drawTriangle(PaintEventArgs e, int x, int y, int distance)
    {
        float angle = 0;

        SolidBrush brs = new SolidBrush(Color.Green);

        PointF[] p = new PointF[3];

        p[0].X = x;

        p[0].Y = y;

        p[1].Y = (float)( x + distance * Math.Cos(angle + Math.PI / 3));

        p[1].X = (float)( y + distance * Math.Sin(angle + Math.PI / 3));

        p[2].Y = (float)( x + distance * Math.Cos(angle - Math.PI / 3));

        p[2].X = (float)( y + distance * Math.Sin(angle - Math.PI / 3));    

        e.Graphics.FillPolygon(brs, p);
    }

Unfortunately, this doesn't even come close. I have drawn equilateral triangles, but the points were always based on the centers of congruent circles. I am trying to find a simpler way. I am sure there must be an obvious problem with this code, but I am trying to learn the math needed as I go, so I don't know what it is. Thanks for your time.

Upvotes: 2

Views: 3172

Answers (1)

MBo
MBo

Reputation: 80287

Try this approach. I assume that for zero angle p[0] is left bottom vertex, p[1] is right bottom (the same horizontal).

(BTW, you have got strange mangling of Y/X)

    p[0].X = x;

    p[0].Y = y;

    p[1].X = (float)( x + distance * Math.Cos(angle));

    p[1].Y = (float)( y + distance * Math.Sin(angle));

    p[2].X = (float)( x + distance * Math.Cos(angle + Math.PI / 3));

    p[2].Y = (float)( y + distance * Math.Sin(angle + Math.PI / 3));  

Upvotes: 2

Related Questions