码迷,mamicode.com
首页 > 移动开发 > 详细

【Android实战】SurfaceView绘制各种效果Demo

时间:2014-12-10 19:55:10      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:bitmap   thread   canvas   android   surfaceview   

1、狂奔的炸弹

public class MySurface extends SurfaceView implements Callback, Runnable {
	SurfaceHolder holder;
	boolean goOn = true;
	int w;
	int h;
	Bitmap bitmap;
	int x;
	int y;
	int bx;
	int by;
	boolean down = true;
	boolean right = true;
	int p = 30;

	public MySurface(Context context, int wi, int hi) {
		super(context);
		// TODO Auto-generated constructor stub
		holder = getHolder();
		holder.addCallback(this);
		setFocusable(true);
		setFocusableInTouchMode(true);
		w = wi;
		h = hi;
		Bitmap obitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.b1);
		bitmap = Bitmap.createScaledBitmap(obitmap, 260, 200, false);
		bx = bitmap.getWidth();
		by = bitmap.getHeight();
		Thread t = new Thread(this);

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		Thread t = new Thread(this);
		t.start();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		goOn = false;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (goOn) {
			myDraw();
			try {
				if (y < h - by && down) {
					y += p;

				} else {
					down = false;
					if (x < w - bx && right) {
						x += p;
					} else {
						right = false;
						if (y > 0 && !down) {
							y -= p;
						} else {

							if (x > 0 && !right) {
								x -= p;
							} else {
								down = true;
								right = true;
							}
						}
					}
				}

				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	Canvas canvas;

	private void myDraw() {
		// TODO Auto-generated method stub
		canvas = holder.lockCanvas();
		if (canvas != null) {
			Paint paint = new Paint();
			paint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
			canvas.drawPaint(paint);
			paint.setXfermode(new PorterDuffXfermode(Mode.SRC));
			canvas.drawColor(Color.GRAY);
			try {
				if (canvas != null) {
					canvas.drawBitmap(bitmap, x, y, null);
				}
			} finally {
				if (canvas != null) {
					holder.unlockCanvasAndPost(canvas);
				}
			}
		}
	}
}



【Android实战】SurfaceView绘制各种效果Demo

标签:bitmap   thread   canvas   android   surfaceview   

原文地址:http://blog.csdn.net/scboyhj__/article/details/41848237

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!