动画可以分为"动"和"画"两个步骤,动画的持久性又可以分为在一定的时间内执行处理任务(画图与字),或不断的重复执行这个过程。
画即画图这个任务(画图)需要一个继承于BitmapField的类处理;
"动"的效果可以交个线程(Thread)去处理,对应于限定时间内的动画和无限次重复执行,线程分为限定次数和无限次的执行处理,但都要有时间间隔,即sleep(间隔时间)。
一、画
画图的任务要交给BitmapField的paint方法来完成。
自定义类 extends BitmapField{
//画图需要重写的paint方法来实现,该方法可以重新对图像进行绘画,位置、大小等
protected void paint(Graphics graphics){
//Call super.paint. This will draw the first background
//frame and handle any required focus drawing.
super.paint(graphics);
//Don't redraw the background if this is the first frame.
//Draw the animation frame.
//具体的图像绘制过程
graphics.drawImage();
}
}
二、动
1 )限定时间的动画
线程要在一定时间内执行完成(有时间间隔),这样可以根据总时长和时间间隔计算出执行的次数,当线程完成了这个次数的运行,即run后,线程就要终止。
new Thread(){
public void run(){
while (_keepGoing){
if (_currentFrame == 0){
oldBitmap = getBitmap();
_theField.setBitmap(_newBitmap);
}
//Increment the frame.
++_currentFrame;
//Invalidate the field so that it is redrawn.
UiApplication.getUiApplication().invokeAndWait(new Runnable(){
public void run(){
_theField.invalidate();
}
});
if (_currentFrame == _totalFrame){
//Reset back to frame 0 if we have reached the end.
_theField.setBitmap(_newBitmap);
_currentFrame = 0;
_keepGoing = false;
}
try{
//Sleep for the current frame delay before
//the next frame is drawn.
sleep(_interval);
} catch (InterruptedException iex){
} //Couldn't sleep.
}
}
}
2 )无限次重复动画
线程进行无限次的执行(有时间间隔),方法run一直都在执行。
new Thread(){
public void run(){
while (_keepGoing){//线程运行
try{
//Invalidate the field so that it is redrawn.
UiApplication.getUiApplication().invokeAndWait(new Runnable(){//回到主线程
public void run(){
_theField.invalidate();//画图类重置,即重新调用paint方法
}
});
try{
//Sleep for the current frame delay before
//the next frame is drawn.
sleep(_image.getFrameDelay(_currentFrame) * 10);//时间间隔
} catch (InterruptedException iex){
} //Couldn't sleep.
//Increment the frame.
++_currentFrame;
if (_currentFrame == _totalFrames){
//Reset back to frame 0 if we have reached the end.
_currentFrame = 0;
++_loopCount;
//Check if the animation should continue.
if (_loopCount == _totalLoops){
_keepGoing = false;//退出线程运行
}
}
} catch (Exception e){
}
}
}
}