4

構造を指定して、三角形を作成する関数を作成しようとしていますRectangle。私は次のコードを持っています:

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

方向が上にある限り、これは機能します。しかし、私には2つの問題があります。ifまず、常に作成する方法はありますが、4つのステートメントを使用する必要がないように、それぞれ0、90、180、または270度回転させるだけです。次に、三角形を黒色で塗りつぶすにはどうすればよいですか?

4

2 に答える 2

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 });  
    }
于 2012-11-25T05:40:25.803 に答える
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);
于 2012-11-24T06:54:40.357 に答える