Working with Graphics |
This page features an example applet that moves one image (a slice of pizza) in front of a background image (a field of stars). This page shows only applet code. The code for an application would be similar, except you would use different code to load the images (as described [somewhere else]).Below are the two images this applet uses.
pizza.gif:
starfield.gif:
Here's the applet in action. Remember that you can click on the applet to stop or start the animation.
The code for performing this animation isn't complex. Essentially, it's the applet animation template, plus the double buffering code you saw on the previous page, plus a few additional lines of code. The additional code loads the images, draws the background image, and then uses a simple algorithm to determine where to draw the moving image. Here is the additional code:
You might think that this program doesn't need to clear the background, since it uses a background image. However, clearing the background is still necessary. One reason is that the applet usually starts drawing before the images are fully loaded. If the pizza image loaded before the background image, you would see parts of multiple pizzas until the background image loaded. Another reason is that if the applet drawing area were wider than the background image, for some reason, then you'd see multiple pizzas to either side of the background image.. . .//Where instance variables are declared: Image stars; Image pizza; . . .//In the init() method: stars = getImage(getDocumentBase(), "images/starfield.gif"); pizza = getImage(getDocumentBase(), "images/pizza.gif"); . . .//In the update() method: void paintFrame(Graphics g) { Dimension d = size(); int w = stars.getWidth(this); int h = stars.getHeight(this); // If we've loaded the background image, draw it. if ((w > 0) && (h > 0)) { g.drawImage(stars, (d.width - w)/2, (d.height - h)/2, this); } w = pizza.getWidth(this); h = pizza.getHeight(this); // If we've loaded the moving image, draw it. if ((w > 0) && (h > 0)) { g.drawImage(pizza, ((frameNumber*5) % (w + d.width)) - w, (d.height - h)/2, this); } }You could solve the first problem by delaying all drawing until both images are fully loaded. The second problem could be solved by scaling the background image to fit the entire applet area. You'll learn how to wait for images to be fully loaded in Improving the Appearance and Performance of Image Animation, later in this lesson.
Working with Graphics |