Java 2D :创建形状夹具



我想知道是否有办法在Java 2D中创建形状夹具。

更具体地说,我正在尝试能够在不同位置用不同的颜色绘制预定义的形状。

我知道您可以使用fill(shape)方法来绘制形状。但是,这似乎需要在我要绘制的坐标处创建一个新形状。

有没有办法每次重复使用相同的形状?还是我必须为每个位置创建一个新形状。

您可以通过转换图形对象的转换矩阵来执行此操作。
假设您有一个名为 shapeShape,其坐标相对于Shape的中心。您还有一个名为 g2Graphics2D实例。
现在,您的代码可能如下所示:

// Set the color of the Shape.
g2.setColor(Color.BLACK);
// Backup the transformation matrix so we can restore it later.
AffineTransform backupTransform = new AffineTransform(g2.getTransform());
// Translate everything that is drawn afterwards by the given coordinates.
// (This will be the new position of the center of the Shape)
g2.translate(53, 27);
// Draw the Shape.
g2.draw(shape);
// Restore the old transform, so that things drawn after this line
// are not affected by the translation.
g2.setTransform(backupTransform);

最新更新