2012-11-24 6 views
4

Rectangle 구조를 주어진 삼각형을 만드는 함수를 만들려고합니다. 나는 다음과 같은 코드를 가지고있다.주어진 사각형 GDI +있는 삼각형을 그리기

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, r.X, r.Y + r.Height, r.X + Width, r.Y + r.Height); // base 
     g.DrawLine(Pens.Black, r.X, r.Y + r.Height, r.X + half, r.Y); // left side 
     g.DrawLine(Pens.Black, r.X + r.Width, r.Y + r.Height, r.X + half, r.Y); // right side 
    } 
} 

이것은 방향이 올라가는 한 작동한다. 하지만 두 가지 문제가 있습니다. 우선, 항상 그것을 그리는 방법이 있습니까? 다만 if 문을 사용하지 않아도되도록 0, 90, 180 또는 270도 회전 시키면됩니까? 둘째, 삼각형을 검정색으로 채우려면 어떻게해야합니까?

+1

'DrawPolygon' 메서드를 호출하여 삼각형을 그려 채우는 것이 좋습니다. – adatapost

답변

1

Graphics.TransformMatrix.Rotate 회전 부분을 해결합니다. 삼각형을 채우기위한 Graphics.FillPolygon.

// 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); 
3

당신은 다음 회전 사각형의 내부에 들어가도록하지만 난 그게 더 생각 정직하게 행렬 변환을 사용하여 확장 균일 한 삼각형을 그릴 수 아래에 해당하는 방법으로 샘플에서

대략 컴파일되지 코드 각 지점을 정의하는 것보다 효과적입니다.

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