C#

【C#】GraphicsPathの領域取得

GraphicsPathを囲む外接四角形の領域はGetBoundsメソッドで取得することができます。

private void Form1_Paint(object sender, PaintEventArgs e)
{
    // パスの作成
    var path = new System.Drawing.Drawing2D.GraphicsPath();

    // 四角形の追加
    path.AddRectangle(new Rectangle(30, 50, 50, 80));
    // 多角形の追加
    path.AddPolygon(
        new Point[]{
            new Point(100, 20),
            new Point(150, 200),
            new Point(60, 70)
        }
        );
    // 円の追加
    path.AddEllipse(150, 30, 50, 50);

    // 描画
    e.Graphics.DrawPath(Pens.Red, path);

    // パスに外接する四角形領域
    RectangleF rect = path.GetBounds();

    // 領域の描画
    e.Graphics.DrawRectangle(Pens.Blue, rect.X, rect.Y, rect.Width, rect.Height);

    ////////////////////////////////////////////////////////////////////////////
    // 文字の追加

    // 文字用にパスの作成
    var pathString = new System.Drawing.Drawing2D.GraphicsPath();
    pathString.AddString(
        "GraphicsPath",
        new FontFamily("Arial"),
        (int)FontStyle.Regular,
        48.0f,
        new Point(20, 250), // 文字の表示位置(左上の座標)
        new StringFormat()
        );

    // パスに外接する四角形領域
    RectangleF rectString = pathString.GetBounds();

    e.Graphics.DrawPath(Pens.Red, pathString);

    // 領域の描画
    e.Graphics.DrawRectangle(Pens.Blue, rectString.X, rectString.Y, rectString.Width, rectString.Height);
    // 文字の表示位置(20, 250)を描画
    e.Graphics.FillEllipse(Brushes.Blue, 15, 245, 10, 10);

}

実行結果

C# GraphicsPath GetBounds

 

GraphicsPathを使うと複数の領域の外接四角形の領域が簡単に取得できるので、パスの領域を描画せずとも、領域の最大/最小の範囲を取得するのに便利です。

 

また、文字の領域も実際に描画している領域を取得できるので、これはこれで便利かも??

 

画像処理のためのC#へ戻る

コメント

タイトルとURLをコピーしました