如何为GraphicsPath应用外边框

时间:2014-06-15 06:15:39

标签: c# winforms

如何为GraphicsPath应用外边框? 我尝试了下面的代码,但它将边框应用于单个矩形而不是整个路径。

我的预期输出截图位于下方。

enter image description here

我试过的Runnable Sample:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.Load += new System.EventHandler(this.Form1_Load);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        GraphicsPath graphicsPath = new GraphicsPath();

        Rectangle rect1 = new Rectangle(20, 20, 100, 30);
        Rectangle rect2 = new Rectangle(20, 50, 40, 20);

        graphicsPath.StartFigure();
        graphicsPath.AddRectangle(rect1);
        graphicsPath.AddRectangle(rect2);

        graphicsPath.CloseAllFigures();
        e.Graphics.FillPath(Brushes.LightGreen, graphicsPath);
        e.Graphics.DrawPath(Pens.DarkGreen, graphicsPath);

    }
}

请告诉我如何实现我的预期输出。在此先感谢。

1 个答案:

答案 0 :(得分:2)

使用多边形而不是矩形绘制形状可获得所需的结果:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.Load += new System.EventHandler(this.Form1_Load);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        GraphicsPath graphicsPath = new GraphicsPath();
        Point[] pts = new Point[] { new Point(20, 20), 
                                    new Point(120, 20), 
                                    new Point(120, 50), 
                                    new Point(60, 50),        
                                    new Point(60, 70), 
                                    new Point(20, 70) };

        graphicsPath.AddPolygon(pts);

        e.Graphics.FillPath(Brushes.LightGreen, graphicsPath);
        e.Graphics.DrawPath(Pens.DarkGreen, graphicsPath);
    }
}