我正在尝试使用 java awt 绘制一个矩形,并通过鼠标拖动使其随鼠标光标旋转。
当我测试它时,矩形旋转得非常快。
我的矩形():
private Rectangle2D rec = new Rectangle2D.Float(x0,y0,w,h);
AffineTransform recTrans = new AffineTransform();
int pivotX = x0+w/2, pivotY = y0+h;
// (0,0) is at the top-left corner
我的油漆组件():
public void paintComponent(Graphics g) {
Graphics2D graph = (Graphics2D) g;
graph.translate(x,y);
graph.transform(recTrans);
graph.fill(rec);
graph.setColor(Color.blue);
graph.draw(rec);
}
我的鼠标拖动事件:
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
previousX = e.getX();
previousY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
currentX = e.getX();
currentY = e.getY();
double angle1 = Math.atan2(currentY-pivotY, currentX-pivotX);
double angle2 = Math.atan2(previousY-pivotY, previousX-pivotX);
double theta = angle2 - angle1;
recTrans.rotate(theta, pivotX, pivotY);
}
});
所以据说场景看起来像:
但是,当我将矩形稍微拖动(θ 小于 10 度)到右侧时,矩形甚至会旋转到枢轴点的底部。
另请注意,矩形旋转但矩形的四个角的坐标尚未更改。
用java做这些转换任务时我很迷茫。