GDI+ 中的图形路径

更新:2007 年 11 月

路径是通过组合直线、矩形和简单的曲线而形成的。请回忆一下 向量图形概述 中的内容,以下基本构造块已被证明对于绘制图形是非常有用的:

  • 直线

  • 矩形

  • 椭圆

  • 弧线

  • 多边形

  • 基数样条

  • 贝塞尔样条

在 GDI+ 中,GraphicsPath 对象您允许将这些构造块序列收集到一个单元中。调用一次 Graphics 类的 DrawPath 方法,就可以绘制出整个序列的直线、矩形、多边形和曲线。下面的插图显示了通过组合一条直线、一段弧、一个贝塞尔样条和一个基数样条而创建的路径。

路径

使用路径

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);

下面的插图显示了该路径。

路径

除了向路径添加直线、矩形和曲线外,还可以向路径添加路径。这就允许您合并现有的路径来形成大型复杂路径。

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

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

您还可以把其他两个项目加入路径:字符串和扇形。扇形是椭圆内的一部分。下面的示例用弧形、基数样条、字符串和扇形创建了路径:

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)

     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);

下面的插图显示了该路径。请注意,不必连接路径;弧形、基数样条、字符串和扇形都是分开的。

路径

请参见

任务

如何:创建用于绘制的 Graphics 对象

参考

System.Drawing.Drawing2D.GraphicsPath

System.Drawing.Point

其他资源

直线、曲线和图形

构造并绘制轨迹