Home > OS >  How to make Triangle obect in Windows Form?
How to make Triangle obect in Windows Form?

Time:03-24

I want to draw/make a triangle graphic that will appear right after when I run the program but I can't figure out the right command. Here's the command I use to make a rectangle object.

private void Form1_Paint(object sender, PaintEventArgs e)
{ 
e.Graphics.FillRectangle(Brushes.Aquamarine, _x, _y, 100, 100); 
} 

Example

So when I make the object, I'll make it move automatically.

I've searched for tutorials but couldn't find anything suitable. Please help.

CodePudding user response:

There is DrawPolygon which probably does what you want, you just need to specify the three vertices of your triangle.

https://docs.microsoft.com/en-us/dotnet/api/system.drawing.graphics.drawpolygon?view=dotnet-plat-ext-6.0

Edit: FillPolygon is probably more in line with what you need, sorry.

https://docs.microsoft.com/en-us/dotnet/api/system.drawing.graphics.fillpolygon?view=dotnet-plat-ext-6.0

CodePudding user response:

You can use FillPolygon and specify 3 triangle points.

e.Graphics.FillPolygon(Brushes.Aquamarine, new Point[] { new Point(150, 100), new Point(100, 200), new Point(200, 200) });

Or you can create a FillTriangle extension method

public static class Extensions
{
    public static void FillTriangle(this Graphics g, PaintEventArgs e, Point p, int size)
    {
        e.Graphics.FillPolygon(Brushes.Aquamarine, new Point[] { p, new Point(p.X - size, p.Y   (int)(size * Math.Sqrt(3))), new Point(p.X   size, p.Y   (int)(size * Math.Sqrt(3))) });
    }
}

And call like this

e.Graphics.FillTriangle(e, new Point(150, 100), 500);

For right triangle use this

e.Graphics.FillPolygon(Brushes.Aquamarine, new Point[] { p, new Point(p.X, p.Y   size * 2), new Point(p.X   size, p.Y   size * 2) });

For obtuse this

e.Graphics.FillPolygon(Brushes.Aquamarine, new Point[] { p, new Point(p.X - size, p.Y   height), new Point(p.X   size, p.Y   height) });
  • Related