6
我有一個矩形,圍繞它的中間旋轉,我有另一個矩形,我想連接到旋轉矩形的右上角。問題是我不知道如何獲得角落,以便第二個矩形總是會卡在那個角落。獲取旋轉矩形的角落
這是我的示例代碼。現在第二個矩形將始終處於相同的位置,這不是我之後的結果。
package Test;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
class Test{
public static void main(String[] args){
new Test();
}
public Test(){
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new Graphic());
frame.setSize(1000,700);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
class Graphic extends JPanel{
private int x, y, windowW, windowH;
private double angle;
private Rectangle rect1, rect2;
private Path2D path;
private Timer timer;
private AffineTransform rotation;
public Graphic(){
windowW = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
windowH = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
path = new Path2D.Double();
rotation = new AffineTransform();
angle = 0;
x = windowW/2;
y = windowH/2;
timer = new Timer(100, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
angle += .1;
if(angle > 360) angle -= 360;
repaint();
}
});
timer.start();
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
rotation.setToTranslation(500, 200);
rotation.rotate(angle, 32, 32);
rect1 = new Rectangle(0, 0, 64, 64);
path = new Path2D.Double(rect1, rotation);
rect2 = new Rectangle(path.getBounds().x, path.getBounds().y, 10, 50);
g2d.fill(path);
g2d.fill(rect2);
}
}
你把'angle'似乎在暗示你要表達它以度約束;然而'rotate'函數以弧度形式獲取其第一個參數。條件'if(angle> 360)angle - = 360'實際上會在到達時引起奇怪的跳躍,並且矩形的旋轉速度比您想要的要快得多。 – Arend