服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

在移动设备上用j2me实现动画


  使用midp(mobile information device profile)的开发人员经常会抱怨用些什么办法才可以在一个midlet上显示动画。 midp 1.0 没有直接提供对动画的支持(正在开发中的midp 2.0支持),但真要是自己去实现,其实也并非是一件很难的事。
  任何动画的最基本的前提,是要在足够快的时间内显示和更换一张张的图片,让人的眼睛看到动的画面效果。图片必须按照顺序画出来。从一张图片到下一张图片之间的变化越小,效果会越好。
  首先要做的,是使用你的图片处理软件(比如ps或者firework)创建一系列相同大小的图片来组成动画。每张图片代表动画一帧。需要制作一定数量的祯--越多的帧会让你的动画看上去越平滑。制作好的图片一定要保存成png(portable network graphics)格式,midp唯一支持的图片格式;有两个办法让你刚做好的图片在midlet上变成动画。第一,把图片都放到一个web服务器上,让midlet下载他们,midp内置的http支持。第二个办法更简单,把图片用midlet打包成jar文件。如果你使用的是j2me开发工具,把png文件放入你的项目文件里面就可以了。
  动画的过程其实更像帐本记录:显示当前帧,然后适当地更换到下一帧。那么使用一个类来完成这个工作应该是很恰当的,那好,我们就先定义一个animatedimage类:
import java.util.*;
import javax.microedition.lcdui.*;
// 定义了一个动画,该动画其实只是一系列相同大小的图片
// 轮流显示,然后模拟出的动画
public class animatedimage extends timertask {;
private canvas canvas;
private image[] images;
private int[][] cliplist;
private int current;
private int x;
private int y;
private int w;
private int h;
// construct an animation with no canvas.
public animatedimage( image[] images ){;
this( null, images, null );
};
// construct an animation with a null clip list.
public animatedimage( canvas canvas, image[]
images ){; this( canvas, images, null );
};
// construct an animation. the canvas can be null,
// but if not null then a repaint will be triggered
// on it each time the image changes due to a timer
// event. if a clip list is specified, the image is
// drawn multiple times, each time with a different
// clip rectangle, to simulate transparent parts.
public animatedimage( canvas canvas, image[] images,
int[][] cliplist ){;
this.canvas = canvas;
this.images = images;
this.cliplist = cliplist;
if( images != null && cliplist != null ){;
if( cliplist.length < images.length ){;
throw new illegalargumentexception();
};
};
if( images != null && images.length > 0 ){;
w = images[0].getwidth();
h = images[0].getheight();
};
};
// move to the next frame, wrapping if necessary.
public void advance( boolean repaint ){;
if( ++current >= images.length ){;
current = 0;
};
if( repaint && canvas != null && canvas.isshown()
){;
canvas.repaint( x, y, w, h );
canvas.servicerepaints();
};
};
// draw the current image in the animation. if
// no clip list, just a simple copy, otherwise
// set the clipping rectangle accordingly and
// draw the image multiple times.
public void draw( graphics g ){;
if( w == 0 || h == 0 ) return;
int which = current;
if( cliplist == null || cliplist[which] == null
){;
g.drawimage( images[which], x, y,
g.top | g.left );
}; else {;
int cx = g.getclipx();
int cy = g.getclipy();
int cw = g.getclipwidth();
int ch = g.getclipheight();
int[] list = cliplist[which];
for( int i = 0; i + 3 <= list.length; i +=
4 ){;
g.setclip( x + list[0], y + list[1],
list[2], list[3] );
g.drawimage( images[which], x, y,
g.top | g.left );
};
g.setclip( cx, cy, cw, ch );
};
};
// moves the animation′s top left corner.
public void move( int x, int y ){;
this.x = x;
this.y = y;
};
// invoked by the timer. advances to the next frame
// and causes a repaint if a canvas is specified.
public void run(){;
if( w == 0 || 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 | graphics.top );
};
};
};
  animatedcanvas 类的代码相当简单,由一个动画导入方法和一个paint方法。canvas画布每次被画,背景都会被擦除,然后循环每个导入的animatedimage对象,直接画到自己身上来(自己扩展了canvas类)。
import java.io.*;
import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
// midlet that displays some simple animations.
// displays a series of birds on the screen and
// animates them at different (random) rates.
public class animationtest extends midlet
implements commandlistener {;
private static final int bird_frames = 7;
private static final int num_birds = 5;
private display display;
private timer timer = new timer();
private animatedimage[] birds;
private random random = new random();
public static final command exitcommand =
new command( "exit",
command.exit, 1 );
public animationtest(){;
};
public void commandaction( command c,
displayable d ){;
if( c == exitcommand ){;
exitmidlet();
};
};
protected void destroyapp( boolean unconditional )
throws midletstatechangeexception {;
exitmidlet();
};
public void exitmidlet(){;
timer.cancel(); // turn it off...
notifydestroyed();
};
// generate a non-negative random number...
private int genrandom( int upper ){;
return( math.abs( random.nextint() ) % upper );
};
public display getdisplay(){; return display; };
// initialize things by creating the canvas and then
// creating a series of birds that are moved to
// random locations on the canvas and attached to
// a timer for scheduling.
protected void initmidlet(){;
try {;
animatedcanvas c = new
animatedcanvas( getdisplay() );
image[] images =
loadframes( "/images/bird",
bird_frames );
int w = c.getwidth();
int h = c.getheight();
birds = new animatedimage[ num_birds ];
for( int i = 0; i < num_birds; ++i ){;
animatedimage b = new
animatedimage( c, images );
birds = b;
b.move( genrandom( w ), genrandom( h ) );
c.add( b );
timer.schedule( b, genrandom( 1000 ),
genrandom( 400 ) );
};
c.addcommand( exitcommand );
c.setcommandlistener( this );
getdisplay().setcurrent( c );
};
catch( ioexception e ){;
system.out.println( "could not
load images" );
exitmidlet();
};
};
// load the bird animation, which is stored as a
// series of png files in the midlet suite.
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;
};
protected void pauseapp(){;
};
protected void startapp()
throws midletstatechangeexception {;
if( display == null ){;
display = display.getdisplay( this );
initmidlet();
};
};
};
  七帧图片的动画,你可以看到一个拍着翅膀的小鸟。midlet显示了5只小鸟,小鸟的位置和刷新速度是随机的。你可以用一些其他的办法来改进这个程序,但这个程序也应该足够能让你上手了。

扫描关注微信公众号