如何使用Graphics2D围绕两个不同的点旋转两个形状



我正在尝试制作一个类似四旋翼的形状,所以我必须围绕不同的点旋转不同的形状。

以下代码段适用于第一个矩形,而不适用于第二个矩形。

public void render(Graphics2D g) {
    // cx and cy is the center of the shape these spin near
    // add prop rotation
    at = g.getTransform();
    at.rotate(Math.toRadians(prop_rotation), cx, cy-42);
    g.setTransform(at);
    // Rect 1 spins correctly!
    g.fillRect(cx-14, cy-45, 28, 6);
    at = g.getTransform();
    at.rotate(Math.toRadians(prop_rotation), cx, cy+38);
    g.setTransform(at);
    // Rect 2 spins around rect 1
    g.fillRect(cx-14, cy+35, 28, 6);
}

图片

那么我该如何使用多个中心呢?

变换是累积的。

首先获取Graphics上下文的副本,然后孤立地对其进行修改。。。

Graphics2D copy = (Graphics2D)g.create();
at = copy.getTransform();
at.rotate(Math.toRadians(prop_rotation), cx, cy-42);
copy.setTransform(at);
// Rect 1 spins correctly!
copy.fillRect(cx-14, cy-45, 28, 6);
copy.dispose();
Graphics2D copy = (Graphics2D)g.create();
at = copy.getTransform();
at.rotate(Math.toRadians(prop_rotation), cx, cy+38);
copy.setTransform(at);
// Rect 2 spins around rect 1
copy.fillRect(cx-14, cy+35, 28, 6);
copy.dispose();

这基本上是Graphics属性的副本,但仍然允许您绘制到相同的"曲面"。更改副本属性不会影响原件。

另一种选择可能是变换形状本身。。。

private Rectangle housing1;
//...
housing1 = new Rectangle(28, 6);
//...
AffineTransform at = new AffineTransform();
at.translate(cx - 14, cy - 45);
at.rotate(Math.toRadians(prop_rotation), cx, cy - 42);
Shape s1 = at.createTransformedShape(housing1);
g.fill(housing1);

这样,您就不会干扰Graphics上下文(这总是很好的),并且您可以获得一个方便的小片段,例如,可以重复用于另一方。。。

at = new AffineTransform();
at.translate(cx-14, cy+35);
at.rotate(Math.toRadians(prop_rotation), cx, cy + 38);
Shape s2 = at.createTransformedShape(housing1);
g.fill(housing2);

最新更新