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

时间:2015-02-11 04:39:16

标签: java geometry 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);
}

Picture

那么我如何在多个中心这样做?

1 个答案:

答案 0 :(得分:1)

转换是累积的。

首先抓取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);