Documentation

The Java™ Tutorials
Hide TOC
Drawing Arbitrary Shapes绘制任意形状
Trail: 2D Graphics
Lesson: Working with Geometry

Drawing Arbitrary Shapes绘制任意形状

You have already learned how to draw most of shapes represented in the java.awt.geom package. 您已经学习了如何绘制java.awt.geom包中表示的大多数形状。To create more complicated geometry, such as polygons, polylines, or stars you use another class from this package, GeneralPath.要创建更复杂的几何体,例如多边形、多段线或星形,请使用此软件包中的另一个类GeneralPath

This class implements the Shape interface and represents a geometric path constructed from lines, and quadratic and cubic curves. 此类实现Shape接口,并表示由直线、二次曲线和三次曲线构造的几何路径。The three constructors in this class can create the GeneralPath object with the default winding rule (WIND_NON_ZERO), the given winding rule (WIND_NON_ZERO or WIND_EVEN_ODD), or the specified initial coordinate capacity. 此类中的三个构造函数可以创建具有默认缠绕规则(WIND_NON_ZERO)、给定缠绕规则(WIND_NON_ZEROWIND_EVEN_ODD)或指定初始坐标容量的GeneralPath对象。The winding rule specifies how the interior of a path is determined.缠绕规则指定如何确定路径的内部。

public void paint (Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    ...
}

To create an empty GeneralPath instance call new GeneralPath() and then add segments to the shape by using the following methods:要创建空的GeneralPath实例,请调用new GeneralPath(),然后使用以下方法将线段添加到形状中:

The following example illustrates how to draw a polyline by using GeneralPath:以下示例说明了如何使用GeneralPath绘制多段线:

// draw GeneralPath (polyline)
int x2Points[] = {0, 100, 0, 100};
int y2Points[] = {0, 50, 50, 0};
GeneralPath polyline = 
        new GeneralPath(GeneralPath.WIND_EVEN_ODD, x2Points.length);

polyline.moveTo (x2Points[0], y2Points[0]);

for (int index = 1; index < x2Points.length; index++) {
         polyline.lineTo(x2Points[index], y2Points[index]);
};

g2.draw(polyline);
This image represents a polyline

This example illustrates how to draw a polygon by using GeneralPath:此示例演示了如何使用GeneralPath绘制多边形:

// draw GeneralPath (polygon)
int x1Points[] = {0, 100, 0, 100};
int y1Points[] = {0, 50, 50, 0};
GeneralPath polygon = 
        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);
This image represents a polygon

Note that the only difference between two last code examples is the closePath() method. 请注意,最后两个代码示例之间的唯一区别是closePath()方法。This method makes a polygon from a polyline by drawing a straight line back to the coordinates of the last moveTo.此方法通过将直线绘制回上一个moveTo的坐标,从多段线生成多边形。

To add a specific path to the end of your GeneralPath object you use one of the append() methods. 要将特定路径添加到GeneralPath对象的末尾,可以使用append()方法之一。The ShapesDemo2D.java code example contains additional implementations of arbitrary shapes.ShapesDemo2D.java代码示例包含任意形状的其他实现。


Previous page: Drawing Geometric Primitives
Next page: Stroking and Filling Graphics Primitives