[摘要]h == 0 ) return; advance( true ); ; ; 你实例化一个AnimatedImage对象的时候你必须给AnimatedImage类的构造方法传一个Image...
h == 0 ) return;
advance( true );
};
};
你实例化一个AnimatedImage对象的时候你必须给AnimatedImage类的构造方法传一个Image对象数组,该数组代表动画的每一帧。使用的所有图片必须具有相同的高度和宽度。
用Image.createImage()方法从jar文件里面加载图片:
private Image[] loadFrames( String name, int frames )
throws IOException {;
Image[] images = new Image[frames];
for( int i = 0; i < frames; ++i ){;
images = Image.createImage( name + i +".png" );
};
return images;
};
你也可以传递一个Canvas对象(可选),和一个剪辑列表(clip list)。如果你指定了一个canvas和使用一个timer来自动更换到动画的下一帧,就如下面的例子代码中一样,canvas在动画向前滚动以后自动被重画(repaint)。不过这样的实现办法是可选的,你可以这样做,也可以让程序选择合适的时候重画canvas。
因为MIDP 1.0不支持透明的图片,AnimatedImage 类使用一个剪辑列表来模拟透明的效果,剪辑列表是图片被剪成的方块区域的系列。图片被画出来的时候分开几次,每次画一个剪辑列表里面的剪辑区域。剪辑列表在帧的基础上被定义好,所以你需要为图片的每一帧创建一个数组。数组的大小应该是4的倍数,因为每一个剪辑面积保持了四个数值:左坐标,顶坐标,宽度以及高度。坐标的原点是整个图片的左上角。需要注意的是使用了剪辑列表会使动画慢下来。如果图片更加复杂的话,你应该使用矢量图片。
AnimatedImage类扩展了java.util.TimerTask,允许你设定一个timer。这里有个例子说明如何使用timer做动画:
Timer timer = new Timer();
AnimatedImage ai = ..... // get the image
timer.schedule( ai, 200, 200 );
每隔大约200毫秒,timer调用AnimatedImage.run()方法一次,这个方法使得动画翻滚到下一个帧。现在我们需要的是让MIDlet来试试显示动画!我们定义一个简单的Canvas类的子类,好让我们把动画“粘贴上去”。
import java.util.*;
import javax.microedition.lcdui.*;
// A canvas to which you can attach one or more
// animated images. When the canvas is painted,
// it cycles through the animated images and asks
// them to paint their current image.
public class AnimatedCanvas extends Canvas {;
private Display display;
private Image offscreen;
private Vector images = new Vector();
public AnimatedCanvas( Display display ){;
this.display = display;
// If the canvas is not double buffered by the
// system, do it ourselves...
if( !isDoubleBuffered() ){;
offscreen = Image.createImage( getWidth(),
getHeight() );
};
};
// Add an animated image to the list.
public void add( AnimatedImage image ){;
images.addElement( image );
};
// Paint the canvas by erasing the screen and then
// painting each animated image in turn. Double
// buffering is used to reduce flicker.
protected void paint( Graphics g ){;
Graphics saved = g;
if( offscreen != null ){;
g = offscreen.getGraphics();
};
g.setColor( 255, 255, 255 );
g.fillRect( 0, 0, getWidth(), getHeight() );
int n = images.size();
for( int i = 0; i < n; ++i ){;
AnimatedImage img = (AnimatedImage)
images.elementAt( i );
img.draw( g );
};
if( g != saved ){;
saved.drawImage( offscreen, 0, 0,
Graphics.LEFT
关键词:用J2ME在移动设备上完成动画