Drawing a triangle in GDI + using a rectangle

I am trying to create a function that will create a triangle, given the structure of the Rectangle . I have the following code:

 public enum Direction { Up, Right, Down, Left } private void DrawTriangle(Graphics g, Rectangle r, Direction direction) { if (direction == Direction.Up) { int half = r.Width / 2; g.DrawLine(Pens.Black, rX, rY + r.Height, rX + Width, rY + r.Height); // base g.DrawLine(Pens.Black, rX, rY + r.Height, rX + half, rY); // left side g.DrawLine(Pens.Black, rX + r.Width, rY + r.Height, rX + half, rY); // right side } } 

This works as long as the direction is up. But I have two problems. First of all, is there a way to always draw it, but just rotate it 0, 90, 180, or 270 degrees, respectively, so as not to use the four if ? Secondly, how can I fill the triangle with black?

+4
source share
2 answers

Graphics.Transform and Matrix.Rotate to solve the rotation part. Graphics.FillPolygon to fill the triangle.

The approximate non-compiled code from the samples to the appropriate methods below:

 // Create a matrix and rotate it 45 degrees. Matrix myMatrix = new Matrix(); myMatrix.Rotate(45, MatrixOrder.Append); graphics.Transform = myMatrix; graphics.FillPolygon(new SolidBrush(Color.Blue), points); 
+1
source

You can draw a homogeneous triangle, then rotate it and scale it using the Matrix transform to fit inside the rectangle, but to be honest, I think there is more work than just defining each point.

  private void DrawTriangle(Graphics g, Rectangle rect, Direction direction) { int halfWidth = rect.Width / 2; int halfHeight = rect.Height / 2; Point p0 = Point.Empty; Point p1 = Point.Empty; Point p2 = Point.Empty; switch (direction) { case Direction.Up: p0 = new Point(rect.Left + halfWidth, rect.Top); p1 = new Point(rect.Left, rect.Bottom); p2 = new Point(rect.Right, rect.Bottom); break; case Direction.Down: p0 = new Point(rect.Left + halfWidth, rect.Bottom); p1 = new Point(rect.Left, rect.Top); p2 = new Point(rect.Right, rect.Top); break; case Direction.Left: p0 = new Point(rect.Left, rect.Top + halfHeight); p1 = new Point(rect.Right, rect.Top); p2 = new Point(rect.Right, rect.Bottom); break; case Direction.Right: p0 = new Point(rect.Right, rect.Top + halfHeight); p1 = new Point(rect.Left, rect.Bottom); p2 = new Point(rect.Left, rect.Top); break; } g.FillPolygon(Brushes.Black, new Point[] { p0, p1, p2 }); } 
+3
source

Source: https://habr.com/ru/post/1448047/


All Articles