import java.awt.Color; import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import javax.swing.JComponent; import javax.swing.JFrame; public class MainClass { public static void main(String[] args) { JFrame jf = new JFrame("Demo"); Container cp = jf.getContentPane(); MyCanvas tl = new MyCanvas(); cp.add(tl); jf.setSize(300, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class MyCanvas extends JComponent { Shape shape; public MyCanvas() { shape = create(); } protected Shape create() { float cm = 72 / 2.54f; return new Rectangle2D.Float(cm, cm, 2 * cm, cm); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setPaint(Color.black); g2.draw(shape); AffineTransform trans = new AffineTransform(); trans.setToTranslation(100, 3); g2.transform(trans); g2.setPaint(Color.red); g2.draw(shape); } }
红色矩形是变换之后的,这个程序可以一目了然setToTranslation的作用,相当于是将整个坐标系平移,比如游戏中使用到的画Sprite
public void draw(Graphics2D g) { // draw background g.drawImage(bgImage, 0, 0, null); AffineTransform transform = new AffineTransform(); for (int i = 0; i < NUM_SPRITES; i++) { Sprite sprite = sprites[i]; // translate the sprite transform.setToTranslation(sprite.getX(), sprite.getY()); // if the sprite is moving left, flip the image if (sprite.getVelocityX() < 0) { transform.scale(-1, 1); transform.translate(-sprite.getWidth(), 0); } // draw it g.drawImage(sprite.getImage(), transform, null); } }
其中,setToTranslation方法就被用来实时定位Sprite的位置,而
transform.translate(-sprite.getWidth(), 0);
这句是干吗的呢?从字面理解是将Sprite往后移动一个宽度(面向为前,背对为后)。因为按y轴镜面翻转之后,实际Sprite是往左移动了一个宽度,因为原先该transform的原点在sprite的左上角。