用四张图片 做动画,图片都放在res文件中了。
public class AnimationView extends View {
//声明属性
Bitmap[] bitmap;
int sleepTime = 1000;
boolean isRunning = true;
int currentImageIndex = 0;
int viewWidth, viewHeight;
Thread thread;
//构造方法
public AnimationView(Context context, AttributeSet attrs) {
super(context, attrs);
bitmap = new Bitmap[4];
bitmap[0] = BitmapFactory.decodeResource(getResources(),
R.drawable.logo1);
bitmap[1] = BitmapFactory.decodeResource(getResources(),
R.drawable.logo2);
bitmap[2] = BitmapFactory.decodeResource(getResources(),
R.drawable.logo3);
bitmap[3] = BitmapFactory.decodeResource(getResources(),
R.drawable.logo4);
MyRunnable myRunnable = new MyRunnable();
thread = new Thread(myRunnable);
thread.start();
}
@Override
protected void onDraw(Canvas canvas) {
Bitmap drawImage = bitmap[currentImageIndex];
int x = (viewWidth - drawImage.getWidth()) / 2;
int y = (viewHeight - drawImage.getHeight()) / 2;
Paint paint = new Paint();
canvas.drawBitmap(drawImage, x, y, paint);
Log.i("animationView", "onDraw x=" + x);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// TODO Auto-generated method stub
super.onSizeChanged(w, h, oldw, oldh);
viewHeight = h;
viewWidth = w;
}
class MyRunnable implements Runnable {
@Override
public void run() {
while (isRunning) {
try {
currentImageIndex++;
if (currentImageIndex >= bitmap.length) {
currentImageIndex = 0;
}
// 工作线程中更新界面调postInvalidate();
// 主线程中更新界面调invalidate();
postInvalidate();
// invalidate();
Log.i("animationView", "currentImageIndex="
+ currentImageIndex);
Thread.currentThread().sleep(sleepTime);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
}