
图 1. BufferedImage 子图形
这个图像是一个以 spriteSize 为边长的正方形。图像其它部分的尺寸值都与这个边长相关。实际上这里只有两个几何实体,一条线和一个圆,都在不同位置和方向重复出现。如果我们创建一个 Line2D.Double 对象代表线,创建一个 Ellipse2D.Double 对象代表圆,那么我们就可以通过移动用户坐标系和画这两个对象中的一个或其它的对象而画出整个图像。
如果是按真正面向对象的方法,应该定义一个类代表一个子图形,可能是作为 BufferedImage 的一个子类,但由于我们是在探索使用 BufferedImage 对象的技巧,因此用一个 createSprite() 方法来画出 BufferedImage 对象上的子图形会更适合我们的目的。因为该方法只是我们的 applet 类的一个成员,所以我们将为 applet 添加数据成员以存储任何需要的数据。您可以把我们将使用的数据成员插入到 applet 类中,如下所示:
double totalAngle; // Current angular position of sprite
double spriteAngle; // Rotation angle of sprite about its center
ImagePanel imagePanel; // Panel to display animation
BufferedImage sprite; // Stores reference to the sprite
int spriteSize = 100; // Diameter of the sprite
Ellipse2D.Double circle; // A circle - part of the sprite
Line2D.Double line; // A line - part of the sprite
// Colors used in sprite
Color[] colors = {Color.red , Color.yellow, Color.green , Color.blue,
Color.cyan, Color.pink , Color.magenta, Color.orange};
java.util.Timer timer; // Timer for the animation
long interval = 50; // Time interval msec between repaints
这些成员的一般用途可以从注释中清楚地看到。下面我们要看一看开发代码时它们是怎样被使用的。
createSprite() 方法需要做的第一件事就是创建 BufferedImage 对象 sprite,然后我们还需要一个 Graphics2D 对象用于在 sprite 图像上绘画。下面就是完成这些操作的代码:
BufferedImage createSprite(int spriteSize)
{
// Create image with RGB and alpha channel
BufferedImage sprite = new BufferedImage(spriteSize, spriteSize,
BufferedImage.TYPE_INT_ARGB);
Gr