-1

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.

Dony KaEf
  • 3
  • 1
  • 3
  • There is no specific method for triangles, but you can use [FillPolygon](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.fillpolygon) – Klaus Gütter Mar 24 '22 at 12:26

2 Answers2

1

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) });

This code will output this

e.Graphics.FillRightTriangle(e, new Point(50, 20), 100);
e.Graphics.FillTriangle(e, new Point(400, 20), 70);
e.Graphics.FillObtuseTriangle(e, new Point(230, 200), 50, 130);

enter image description here

AKK
  • 44
  • 4
  • I tried your first and second code both of them work but I don't understand why the Triangle object was blinking. Do you know why it's happening? – Dony KaEf Mar 24 '22 at 15:11
  • If you don't want it to blink, you need to set the DoubleBuffered property of your form to True. I highly recommend drawing in the PictureBox control, which is double-buffered by default and allows you to control your drawing region much more simply. If you want to stretch the PictureBox to full screen, you need to set the Dock property to Fill – AKK Mar 24 '22 at 16:00
  • I got it. Thanks for your help. – Dony KaEf Mar 24 '22 at 16:39
0

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

https://learn.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://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.fillpolygon?view=dotnet-plat-ext-6.0

Raphael
  • 810
  • 6
  • 18