绘制任意形状
您已经学习了如何绘制java.awt.geom
程序包中表示的大多数形状。要创建更复杂的几何图形(例如多边形,折线或星形),请使用此包GeneralPath
中的另一个类。
此类实现Shapeinterface,并表示由直线,二次曲线和三次曲线构成的几何路径。此类中的三个构造函数可以使用默认绕线规则(WIND_NON_ZERO
),给定绕线规则(WIND_NON_ZERO
或WIND_EVEN_ODD
)或指定的初始坐标容量来创建GeneralPath对象。缠绕规则指定如何确定路径的内部。
public void paint (Graphics g) {
Graphics2D g2 = (Graphics2D) g;
...
}
若要创建一个空的GeneralPath
实例,请调用new GeneralPath()
,然后使用以下方法将线段添加到形状中:
-
moveTo(float x, float y)
–将路径的当前点移至给定点 -
lineTo(float x, float y)
–将线段添加到当前路径 -
quadTo(float ctrlx, float ctrly, float x2, floaty2)
–将二次曲线段添加到当前路径 -
curveTo(float ctrlx1, float ctrly1, float ctrlx2, float ctrly2, float x3, floaty3)
–将三次曲线段添加到当前路径 -
closePath()
–关闭当前路径
以下示例说明了如何使用GeneralPath
绘制折线:
//绘制 GeneralPath(折线) | |
int x2Points [20] = {0, 100, 0, 100}; int y2Points [21] = {0, 50, 50, 0}; GeneralPath 折线= 新的 GeneralPath(GeneralPath.WIND_EVEN_ODD,x2Points.length); polyline.moveTo(x2Points [22],y2Points [23]); for(int index = 1; index <x2Points.length; index){ polyline.lineTo(x2Points[index], y2Points[index]); }; g2.draw(polyline); |
本示例说明了如何使用GeneralPath
绘制多边形:
//绘制 GeneralPath(多边形) | |
int x1Points [29] = {0, 100, 0, 100}; int y1Points [30] = {0, 50, 50, 0}; GeneralPath 多边形= new GeneralPath(GeneralPath.WIND_EVEN_ODD, x1Points.length); polygon.moveTo(x1Points[0], y1Points[0]); for(int index = 1; index <x1Points.length; index){ polygon.lineTo(x1Points[index], y1Points[index]); }; polygon.closePath(); g2.draw(polygon); |
请注意,最后两个代码示例之间的唯一区别是closePath()
方法。此方法通过将一条直线返回到最后一个moveTo
的坐标来从折线制作多边形。
要将特定路径添加到GeneralPath
对象的末尾,请使用append()
方法之一。 ShapesDemo2D.java代码示例包含任意形状的其他实现。