GDI+ 中的图形路径
路径通过组合线条、矩形和简单曲线形成。 请回顾 矢量图形概述,以下基本构成模块被证明是绘制图片中最有用的:
直线
矩形
椭圆
弧线
多边形
基数样条
贝塞尔自由绘制曲线
在 GDI+ 中,GraphicsPath 对象允许将这些构建基块的序列收集到单个单元中。 然后,可以使用对 Graphics 类的 DrawPath 方法的一个调用绘制整个线条、矩形、多边形和曲线序列。 下图显示了通过组合线条、弧线、贝塞尔样条和基数样条创建的路径。
使用路径
GraphicsPath 类提供以下方法来创建要绘制的项序列:AddLine、AddRectangle、AddEllipse、AddArc、AddPolygon、AddCurve(用于基数自由绘制曲线)和 AddBezier。 每个方法都重载;也就是说,每个方法都支持多个不同的参数列表。 例如,AddLine 方法的一个变体接收四个整数,AddLine 方法的另一个变体接收两个 Point 对象。
向路径添加线条、矩形和 Bézier 样条的方法具有复数配套方法,用于在单个调用中向路径添加多个项:AddLines、AddRectangles和 AddBeziers。 此外,AddCurve 和 AddArc 方法具有配套方法,AddClosedCurve 和 AddPie,向路径添加封闭曲线或饼图。
若要绘制路径,需要 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)
可以向路径添加另外两个项:字符串和馅饼。 馅饼是椭圆内部的一部分。 以下示例从弧线、基数自由绘制曲线、字符串和扇形创建路径:
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)
下图显示了路径。 请注意,路径不必相连;弧线、基数自由绘制曲线、字符串和扇形彼此分隔。