2012-11-24 204 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 
    } 
} 

只要方向朝上,這就行得通了。但我有兩個問題。首先,有沒有辦法總是把它畫出來,但分別旋轉0,90,180或270度,以免不必使用四個if陳述?其次,我怎樣才能用黑色填充三角形?

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