GDI+ 中的图形路径

路径由直线、矩形和简单曲线组合而成。 回顾一下矢量图形概述,以下基本构建基块已被证明对绘制图片最有用:

  • 矩形

  • 椭圆

  • 弧线

  • Polygon(多边形)

  • 基数自由绘制曲线

  • 贝塞尔自由绘制曲线

在 GDI+ 中,使用 GraphicsPath 对象可以将这些构建基块的序列收集到一个单元中。 然后可以通过调用一次 Graphics 类的 DrawPath 方法来绘制线条、矩形、多边形和曲线的整个序列。 下图显示了通过组合直线、弧线、贝塞尔自由绘制曲线和基数自由绘制曲线创建的路径。

Image of a single-line path, starting from a straight line and continuing into different shapes.

使用路径

GraphicsPath 类提供以下方法来创建要绘制的项序列:AddLineAddRectangleAddEllipseAddArcAddPolygonAddCurve(用于基数自由绘制曲线)和 AddBezier。 其中每个方法都是重载的;也就是说,每个方法都支持多个不同的参数列表。 例如,AddLine 方法的一个变体接收四个整数,而 AddLine 方法的另一个变体接收两个 Point 对象。

将直线、矩形和贝塞尔自由绘制曲线添加到路径的方法具有多个配套方法,可用于在一次调用中将多个项添加到路径:AddLinesAddRectanglesAddBeziers。 此外,AddCurveAddArc 方法具有配套方法 AddClosedCurveAddPie,它们可向路径添加闭合曲线或扇形。

若要绘制路径,需要一个 Graphics 对象、一个 Pen 对象和一个 GraphicsPath 对象。 Graphics 对象提供 DrawPath 方法,而 Pen 对象存储用于呈现路径的线条的属性,例如宽度和颜色。 GraphicsPath 对象存储构成路径的直线和曲线序列。 Pen 对象和 GraphicsPath 对象作为参数传递给 DrawPath 方法。 以下示例绘制一个由直线、椭圆形和贝塞尔自由绘制曲线组成的路径:

myGraphicsPath.AddLine(0, 0, 30, 20);
myGraphicsPath.AddEllipse(20, 20, 20, 40);
myGraphicsPath.AddBezier(30, 60, 70, 60, 50, 30, 100, 10);
myGraphics.DrawPath(myPen, myGraphicsPath);
myGraphicsPath.AddLine(0, 0, 30, 20)
myGraphicsPath.AddEllipse(20, 20, 20, 40)
myGraphicsPath.AddBezier(30, 60, 70, 60, 50, 30, 100, 10)
myGraphics.DrawPath(myPen, myGraphicsPath)

下图显示了该路径。

Image of a path displayed within a graph.

除了向路径添加直线、矩形和曲线外,还可以向路径添加路径。 这样,就可以将现有路径组合在一起,形成大型复杂路径。

myGraphicsPath.AddPath(graphicsPath1, false);
myGraphicsPath.AddPath(graphicsPath2, false);
myGraphicsPath.AddPath(graphicsPath1, False)
myGraphicsPath.AddPath(graphicsPath2, False)

可以向路径添加另外两种项:字符串和扇形。 扇形是椭圆形内部的一部分。 以下示例从弧线、基数自由绘制曲线、字符串和扇形创建路径:

GraphicsPath myGraphicsPath = new GraphicsPath();

Point[] myPointArray =
{
    new Point(5, 30),
    new Point(20, 40),
    new Point(50, 30)
};

FontFamily myFontFamily = new FontFamily("Times New Roman");
PointF myPointF = new PointF(50, 20);
StringFormat myStringFormat = new StringFormat();

myGraphicsPath.AddArc(0, 0, 30, 20, -90, 180);
myGraphicsPath.StartFigure();
myGraphicsPath.AddCurve(myPointArray);
myGraphicsPath.AddString("a string in a path", myFontFamily,
   0, 24, myPointF, myStringFormat);
myGraphicsPath.AddPie(230, 10, 40, 40, 40, 110);
myGraphics.DrawPath(myPen, myGraphicsPath);
Dim myGraphicsPath As New GraphicsPath()

Dim myPointArray As Point() = { _
   New Point(5, 30), _
   New Point(20, 40), _
   New Point(50, 30)}

Dim myFontFamily As New FontFamily("Times New Roman")
Dim myPointF As New PointF(50, 20)
Dim myStringFormat As New StringFormat()

myGraphicsPath.AddArc(0, 0, 30, 20, -90, 180)
myGraphicsPath.StartFigure()
myGraphicsPath.AddCurve(myPointArray)
myGraphicsPath.AddString("a string in a path", myFontFamily, _
   0, 24, myPointF, myStringFormat)
myGraphicsPath.AddPie(230, 10, 40, 40, 40, 110)
myGraphics.DrawPath(myPen, myGraphicsPath)

下图显示了该路径。 请注意,路径不必相连;弧线、基数自由绘制曲线、字符串和扇形彼此分隔。

Paths

另请参阅