Java 2D:创建形状夹具
Java 2D : Creating Shape Fixtures
我想知道是否有办法在 Java 2D 中创建形状夹具。
更具体地说,我试图能够在不同位置用不同颜色绘制预定义形状。
我知道您可以使用 fill(shape)
方法来绘制形状。
但是,这似乎需要在我要绘制的坐标处创建一个新形状。
有没有办法每次重复使用相同的形状?或者我必须为每个位置创建一个新形状。
您可以通过平移图形对象的变换矩阵来做到这一点。
假设您有一个名为 shape
的 Shape
,其坐标相对于 Shape
的中心。您还有一个名为 g2
的 Graphics2D
实例。
现在您的代码可能如下所示:
// 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);
我想知道是否有办法在 Java 2D 中创建形状夹具。
更具体地说,我试图能够在不同位置用不同颜色绘制预定义形状。
我知道您可以使用 fill(shape)
方法来绘制形状。
但是,这似乎需要在我要绘制的坐标处创建一个新形状。
有没有办法每次重复使用相同的形状?或者我必须为每个位置创建一个新形状。
您可以通过平移图形对象的变换矩阵来做到这一点。
假设您有一个名为 shape
的 Shape
,其坐标相对于 Shape
的中心。您还有一个名为 g2
的 Graphics2D
实例。
现在您的代码可能如下所示:
// 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);