2012-11-24 159 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 }); 
    }