Activity类
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MySurfaceView(this));
}
}
SurfaceView类:
public class MySurfaceView extends SurfaceView implements Callback{
public SurfaceHolder holder;
public Canvas canvas;
public Bitmap image[]=null;
public int temp=0;
public MySurfaceView(Context context) {
super(context);
Bitmap tempImage=BitmapFactory.decodeResource(context.getResources(), R.drawable.piranha_plant);
image=new Bitmap[4];
image[0]=Bitmap.createBitmap(tempImage, 0, 0, tempImage.getWidth()/4, tempImage.getHeight());
image[1]=Bitmap.createBitmap(tempImage, tempImage.getWidth()/4, 0, tempImage.getWidth()/4, tempImage.getHeight());
image[2]=Bitmap.createBitmap(tempImage, 2*tempImage.getWidth()/4, 0, tempImage.getWidth()/4, tempImage.getHeight());
image[3]=Bitmap.createBitmap(tempImage, 3*tempImage.getWidth()/4, 0, tempImage.getWidth()/4, tempImage.getHeight());
this.setFocusable(true);//获得焦点
this.setFocusableInTouchMode(true);//获得焦点的触屏焦点也可用
requestFocus();//获得焦点请求
holder=getHolder();
holder.addCallback(this);
}
public void onDraw(){
canvas=holder.lockCanvas();
try {
canvas.save();
canvas.drawBitmap(image[temp], temp*20, 0, new Paint());
canvas.restore();
} catch (Exception e) {
e.printStackTrace();
}finally{
holder.unlockCanvasAndPost(canvas);
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
onDraw();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_DPAD_RIGHT){
if(temp<4){
temp++;
onDraw();
}
}else if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT){
temp--;
onDraw();
}
return super.onKeyDown(keyCode, event);
}
}
大家可以随便弄一张连续四帧的图片,名字搞好就可以了。想过绝对会出乎你的意料
所以由此来讨论canvas.save()和canvas.retore()到底是如何保存、如何恢复,什么时候保存、什么时候恢复..
希望大家多发表意见???