posted by David Chen at May 06, 2009 12:27 AM
//定义一个小狗跳步的view,注意,在res中有一个图片,是一个小狗跑步的3个不同动作。图片宽105,高26,分35长为一个子图。
public class Dog extends View {
private AnimationDrawable ad;
// 定义一个对象
public Dog(Context context) {
super(context);
// TODO Auto-generated constructor stub
ad = new AnimationDrawable();
// 分配空间
Bitmap p = BitmapFactory.decodeResource(context.getResources(), R.drawable.dog);
//从res中加载小狗的图片
Log.d("Bitmap p", "" + p.getWidth() + " " + p.getHeight());
Bitmap p1 = Bitmap.createBitmap(p, 0, 0, 35, 26);
//Bitmap.createBitmap(p, left, top, width, height); 从p这个图中的点左上角(0,26)到点右下角(35,0)中的矩形图象,注意left, top, width, height参数和Rect形的参数是有不同的。
ad.addFrame(new BitmapDrawable(p1), 50);
Bitmap p2 = Bitmap.createBitmap(p, 35, 0, 35, 26);
ad.addFrame(new BitmapDrawable(p2), 50);
Bitmap p3 = Bitmap.createBitmap(p, 70, 0, 35, 26);
ad.addFrame(new BitmapDrawable(p3), 50);
Log.d("frame count", "" + ad.getNumberOfFrames());
ad.setOneShot( false );
this.setBackgroundDrawable(ad);
// 不能在这里用 ad.start(); ad.start()不能在Activity.onCreate事件未执行完就调用。但可以用在比如点击按纽后就调用等。
}
public AnimationDrawable getAnimationDrawable()
{
return ad;
}
}