page prйcйdantetable des matiиrespage suivante

Анимиране на изображения в аплети

Изображенията могат да бъдат твърде обемни и се зареждат инкрементално. При бавна връзка зареждането им може да отнеме доста време.  Методът drawImage() позволява рисуването им, когато те са заредени частично, което би довело до странни ефекти при анимацията. В долния пример се взимат мерки анимацията да започне след пълното зареждане на изображенията T6.gif и T7.gif :

 

import java.awt.*;
import java.applet.*;


public class AnimEx6 extends Applet implements Runnable {
int frame;
int delay;
int step1=5,step2=2;
Thread animator;

Dimension offDimension;
Image offImage;
Graphics offGraphics;

Image image[] = new Image[2];
AudioClip clip;


public void init() {
String str = getParameter("fps");
int fps = (str != null) ? Integer.parseInt(str) : 10;
delay = (fps > 0) ? (1000 / fps) : 100;
image[0] = getImage(getCodeBase(),"images/T6.gif");
image[1] = getImage(getCodeBase(),"images/T7.gif");
clip = getAudioClip(getCodeBase(),"images/bubble.au");

}

/**
Create a thread and start it.
*/
public void start() {
animator = new Thread(this);
animator.start();
}

/**
* the main animation.
*/
public void run() {
// Remember the starting time
long tm = System.currentTimeMillis();
while (Thread.currentThread() == animator) {
// Display the next frame of animation.
repaint();

// Delay depending on how far we are behind.
try {
tm += delay;
Thread.sleep(Math.max(0,tm-System.currentTimeMillis()));
} catch (InterruptedException e) {break; }

// Advance the frame
frame++;
}
}

/**
* called when the applet is no longer visible.
*/
public void stop() {
animator = null;
offImage = null;
offGraphics = null;
}

/**
* Update a frame of animation.
*/
public void update(Graphics g) {
Color fgr=getForeground();
Dimension d = getSize();

// Create the offscreen graphics context
if ((offGraphics == null)
|| (d.width != offDimension.width)
|| (d.height != offDimension.height))
{ offDimension = d;
offImage = createImage(d.width, d.height);
offGraphics = offImage.getGraphics();
}

// Erase the previous image
offGraphics.setColor(getBackground());
offGraphics.fillRect(0, 0, d.width, d.height);
offGraphics.setColor(fgr);

// Paint the frame into the image
paintFrame(offGraphics);

// Paint the image onto the screen
g.drawImage(offImage, 0, 0, this);
}


public void paint(Graphics g) {
update(g);
}

/**
* Paint a frame of animation.
*/
public void paintFrame(Graphics g) {
int wdth = getSize().width;
int hght = getSize().height;
if((image[0].getWidth(this) > 0) &&
(image[0].getHeight(this) > 0) &&
(image[1].getWidth(this) > 0) &&
(image[1].getHeight(this) > 0) )
{ //the image is loaded
g.drawImage(image[frame%2],wdth-((frame*step1)%wdth),hght/4,this);
if(wdth-((frame*step1)%wdth)<=step1) clip.play();
g.drawImage(image[frame%2],(frame*step2)%wdth,hght/2,this);
if((frame*step2)%wdth<step2) clip.play();
}
}
}
  No Java Support

 

page prйcйdantetable des matiиrespage suivante