我使用drawPolygon()
创建了星形,但我想从星形的中心点和屏幕的中心旋转它。
以下是我从中心旋转星号的代码:
@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
AffineTransform origX = g2d.getTransform();
AffineTransform newX = (AffineTransform) origX.clone();
newX.rotate(Math.toRadians(angle), x, y + 62); // Rotate about center of the star
g2d.setTransform(newX);
g2d.drawPolygon(starX, starY, 5);
g2d.dispose();
g.dispose();
}
如果我更换:
newX.rotate(Math.toRadians(angle), x, y + 62);
到
newX.rotate(Math.toRadians(angle), this.getWidth() / 2, this.getHeight() / 2);
我可以从屏幕中心旋转它。
但是,我想同时实现这两种效果。 即:就像围绕太阳旋转的地球以及自己的轴一样。
我尝试创建另一个AffineTransform
对象,但当我使用g2d.setTransform(newObj);
任何建议都会非常有帮助。 谢谢。
如果您想查看
,请参阅以下完整代码import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
public class Star extends Applet implements Runnable{
private int[] starX;
private int[] starY;
private Thread mainThread;
private int x;
private int y;
private int angleFromCenterShape;
@Override
public void init() {
this.setSize(800, 480);
x = 250;
y = 150;
angleFromCenterShape = 0;
starX = new int[5];
starY = new int[5];
mainThread = new Thread(this);
mainThread.start();
this.setBackground(Color.BLACK);
}
@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
AffineTransform origX = g2d.getTransform();
AffineTransform newX = (AffineTransform) origX.clone();
newX.rotate(Math.toRadians(angleFromCenterShape), x, y + 65); //Rotate about center of the star
g2d.setTransform(newX);
g2d.setColor(Color.red);
g2d.fillPolygon(starX, starY, 5);
g2d.dispose();
g.dispose();
}
@Override
public void run() {
while(true){
angleFromCenterScreen = (angleFromCenterScreen + 1) % 360; // angle loop from 0 to 36o
initStar();
try{
Thread.sleep(30);
}catch(Exception e){}
repaint();
}
}
private void initStar(){
starX[0] = x;
starX[1] = x - 50;
starX[2] = x + 75;
starX[3] = x - 75;
starX[4] = x + 50;
starY[0] = y;
starY[1] = y + 130;
starY[2] = y + 50;
starY[3] = y + 50;
starY[4] = y + 130;
}
}
答案 0 :(得分:0)
我找到了解决问题的方法,但这不是一个确切的解决方案。
但是,在同一个rotate()
对象上添加另一个AffineTransform
会模仿2次旋转
@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
AffineTransform origX = g2d.getTransform();
AffineTransform newX = (AffineTransform) origX.clone();
newX.rotate(Math.toRadians(angle), this.getWidth() / 2, this.getHeight() / 2); // Rotate from the center of screen
newX.rotate(Math.toRadians(angle), x, y + 65); // Rotate from the center of the shape
g2d.setTransform(newX);
g2d.setColor(Color.red);
g2d.fillPolygon(starX, starY, 5);
g2d.dispose();
g.dispose();
}