从线条、曲线和形状创建图形

若要创建路径,请构造 GraphicsPath 对象,然后调用 AddLineAddCurve 等方法将基元添加到路径。

以下示例创建一个具有单个弧线的路径。弧线的扫描角度为 –180 度,在默认坐标系中是逆时针的。

Pen pen(Color(255, 255, 0, 0));
GraphicsPath path;
path.AddArc(175, 50, 50, 50, 0, -180);
graphics.DrawPath(&pen, &path);

以下示例创建一个包含两个图形的路径。 第一个图形是一条弧线,后跟一条直线。 第二个图是一条线,后跟一条曲线,后跟一条线。 第一个图形保持打开状态,第二个图形关闭。

Point points[] = {Point(40, 60), Point(50, 70), Point(30, 90)};

Pen pen(Color(255, 255, 0, 0), 2);
GraphicsPath path;

// The first figure is started automatically, so there is
// no need to call StartFigure here.
path.AddArc(175, 50, 50, 50, 0.0f, -180.0f);
path.AddLine(100, 0, 250, 20);

path.StartFigure();
path.AddLine(50, 20, 5, 90);
path.AddCurve(points, 3);
path.AddLine(50, 150, 150, 180);
path.CloseFigure();

graphics.DrawPath(&pen, &path);

除了向路径添加线条和曲线外,还可以添加封闭形状:矩形、椭圆形、馅饼和多边形。 以下示例创建一个路径,其中包含两条线、一个矩形和一个椭圆。 该代码使用笔绘制路径,使用画笔填充路径。

GraphicsPath path;
Pen          pen(Color(255, 255, 0, 0), 2);
SolidBrush   brush(Color(255, 0, 0, 200));

path.AddLine(10, 10, 100, 40);
path.AddLine(100, 60, 30, 60);
path.AddRectangle(Rect(50, 35, 20, 40));
path.AddEllipse(10, 75, 40, 30);

graphics.DrawPath(&pen, &path);
graphics.FillPath(&brush, &path);

上一示例中的路径有三个图。 第一个图由两条线组成,第二个图由矩形组成,第三个图由椭圆组成。 即使没有调用 GraphicsPath::CloseFigureGraphicsPath::StartFigure,固有封闭的形状(如矩形和椭圆)也被视为单独的图形。