public class MySurfaceView extends SurfaceView implementsCallback, Runnable {privateThread th;privateSurfaceHolder sfh;private intSH, SW;privateCanvas canvas;privatePaint p;privatePaint p2;privateResources res;privateBitmap bmp;private int bmp_x = 100, bmp_y = 300;private booleanLEFT, RIGHT;private int animation_left[] = { 0, 1, 2};private int animation_right[] = { 3, 4, 5};private int animation_init[] =animation_left;private intanim_count;//一张图上图的数量
private static final int bm_count = 6;private booleanthreadFlag;publicMySurfaceView(Context context) {super(context);this.setKeepScreenOn(true);
res= this.getResources();
bmp=BitmapFactory.decodeResource(res, R.drawable.move_bitmap);
sfh= this.getHolder();
sfh.addCallback(this);
p= newPaint();
p.setColor(Color.YELLOW);
p2= newPaint();
p2.setColor(Color.RED);
p.setAntiAlias(true);
setFocusable(true);
}public voidsurfaceCreated(SurfaceHolder holder) {
SH= this.getHeight();
SW= this.getWidth();
threadFlag= true;
th= new Thread(this);
th.start();
}public voiddraw() {
canvas=sfh.lockCanvas();if (canvas != null) {
canvas.drawRect(0, 0, SW, SH, p);
canvas.save();
canvas.drawText("奋斗的小猿", bmp_x + 5, bmp_y - 10, p2);
canvas.clipRect(bmp_x, bmp_y, bmp_x+ bmp.getWidth() / bm_count, bmp_y +bmp.getHeight());if (animation_init ==animation_left) {
canvas.drawBitmap(bmp, bmp_x- animation_left[anim_count] * (bmp.getWidth() /bm_count), bmp_y, p);
}else if (animation_init ==animation_right) {
canvas.drawBitmap(bmp, bmp_x- animation_right[anim_count] * (bmp.getWidth() /bm_count), bmp_y, p);
}
canvas.restore();
sfh.unlockCanvasAndPost(canvas);
}
}public voidcycle() {if(LEFT) {
bmp_x-= 5;if (bmp_x <= 0) {
bmp_x= 0;
}
}else if(RIGHT) {
bmp_x+= 5;if ((bmp_x + bmp.getWidth() / bm_count) >=SW) {
bmp_x= SW - bmp.getWidth() /bm_count;
}
}if (LEFT ||RIGHT) {if (anim_count < 2) {
anim_count++;
}else{
anim_count= 0;
}
}if (LEFT == false && RIGHT == false) {
anim_count= 0;
}
}
@Overridepublic booleanonTouchEvent(MotionEvent event) {if (event.getAction() ==MotionEvent.ACTION_DOWN) {if (event.getX() < 100) {if (LEFT == false) {
animation_init=animation_left;
LEFT= true;
}
}else if (event.getX() > (SW - 100)) {if (RIGHT == false) {
animation_init=animation_right;
RIGHT= true;
}
}
}else if (event.getAction() ==MotionEvent.ACTION_UP) {if(LEFT) {
LEFT= false;
}else if(RIGHT) {
RIGHT= false;
}
}return true;
}public voidrun() {while(threadFlag) {
draw();
cycle();try{
Thread.sleep(20);
}catch(Exception ex) {
}
}
}public void surfaceChanged(SurfaceHolder holder, int format, int width, intheight) {
}public voidsurfaceDestroyed(SurfaceHolder holder) {
threadFlag= false;
}
}