android自定义SurfaceView实现跑男动画

先看效果:



代码实现:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * 奔跑的小人
 * 
 * @author shaoshuai
 * 
 */
public class RunManView extends SurfaceView {
	private SurfaceHolder holder;
	/** 画布 */
	private Canvas mCanvas;
	/** 画笔 */
	private Paint mPaint;
	/** 视图宽度 */
	private int mWidth;
	/** 视图高度 */
	private int mHeight;

	/** 背景 */
	private Bitmap mBg1;
	/** 奔跑的小人 */
	private Bitmap mPlay1;
	/** 每一帧的动画时间 */
	private int Time = 50;
	/** 当前图片的动画帧 */
	private int mPicPosition = 0;// 动画共10帧,开始为0

	/** 执行动作 */
	private Runnable runnable = new Runnable() {
		@Override
		public void run() {
			myDraw();
		}
	};

	public RunManView(Context context, AttributeSet attrs) {
		super(context, attrs);
		holder = this.getHolder();
		holder.addCallback(callBack);

		mPaint = new Paint();
		mPaint.setColor(Color.YELLOW);

		BitmapFactory.Options ops = new BitmapFactory.Options();
		mBg1 = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg1, ops);
		mPlay1 = BitmapFactory.decodeResource(getResources(), R.drawable.dartman, ops);
	}

	SurfaceHolder.Callback callBack = new SurfaceHolder.Callback() {
		@Override
		public void surfaceCreated(SurfaceHolder holder) {

		}

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
			// 获取屏幕宽高
			mWidth = width;
			mHeight = height;
			// mRect = new Rect(0, 0, mWidth, mHeight);
			new Thread(runnable).start();
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {

		}
	};

	private void myDraw() {
		int toLeft = 300;// 距离左侧宽度
		int toTop = mHeight - 100;// 距离顶部高度

		if (toLeft > mWidth) {
			toLeft = 0;
		}
		while (true) {
			try {
				Rect mClipRect = new Rect(toLeft, toTop, toLeft + mPlay1.getWidth() / 10, toTop - mPlay1.getHeight());
				mCanvas = holder.lockCanvas();
				if (mCanvas != null) {
					// 画背景
					mCanvas.drawBitmap(mBg1, null, new Rect(0, 0, mWidth, mHeight), mPaint);
					mCanvas.save();// 保存当前状态
					mCanvas.clipRect(mClipRect);// 裁剪区域
					// 画小人
					mCanvas.drawBitmap(mPlay1, toLeft - mPicPosition * mPlay1.getWidth() / 10,
							toTop - mPlay1.getHeight(), mPaint);
					mCanvas.restore();// 取出保存状态
					mPicPosition++;// 步子加1
					// 无限循环跑动
					if (mPicPosition > 9) {
						mPicPosition = 0;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (mCanvas != null) {
					holder.unlockCanvasAndPost(mCanvas);
				}
			}
			try {
				Thread.sleep(Time);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}



相应的资源文件:

dartman.png




你可能感兴趣的:(android,自定义控件,SurfaceView)