[英]How to rotate two shapes around two different points with 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.