【Android实战】SurfaceView绘制各种效果Demo
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); } } } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。