甲Rectangle
不能轉動,其邊緣總是在平行於軸線。但是你可以旋轉和平移繪製形狀的座標系。來自Graphics2D
API文檔。
傳遞給Graphics2D對象的所有座標都在獨立於設備的稱爲用戶空間的座標系中指定,該座標系由應用程序使用。 Graphics2D對象包含一個AffineTransform對象作爲其渲染狀態的一部分,該對象定義瞭如何將座標從用戶空間轉換爲設備空間中與設備相關的座標。
Graphics2D
還提供了兩個方法,在這個任務中是有用的:translate
即移動座標和rotate
,好吧,旋轉系統的原點。
package graphics;
import javax.swing.*;
import java.awt.*;
/**
* Earth Hour
*/
public class RotateRect extends JFrame {
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
public RotateRect() {
this.setSize(WIDTH, HEIGHT);
this.setTitle("Rotate Rectangles");
this.setContentPane(new JPanel() {
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// Background: White
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, this.getWidth(), this.getHeight());
// Draw "Earth": Center(200, 400), Radius=200
g2.setColor(Color.BLACK);
g2.fillOval(0, 200, 400, 400);
// Move origin to center of the canvas (surface of earth)
g2.translate(200, 200);
// Rotate the coordinate system, relative to the center of earth.
// note x, y are in the translated system
// Transforms are accumulative
g2.rotate(-Math.PI/6, 0, 200);
// Fill a rectangle with top-left corner at (-20, 80) in the rotated system
// It's important to make the rectangle symmetrical to the y-axis, otherwise the building looks
// funny.
// Also, make the building "sunk" a little, so that it's fully on the ground.
g2.fillRect(-20, -80, 40, 100);
g2.rotate(Math.PI/3, 0, 200);
g2.fillRect(-20, -80, 40, 100);
g2.rotate(-Math.PI/6, 0, 200);
g2.fill(new Rectangle(-20, -80, 40, 100));
}
});
}
public static void main(String [] args) {
RotateRect rr = new RotateRect();
rr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EventQueue.invokeLater(()->rr.setVisible(true));
}
}
你可以把你的代碼,讓任何人都可以幫助你嗎? – esprittn
是的。我已經把代碼的一部分,我用於垂直 –