【Android】SurfaceView中使用线程绘制图形
1 package com.example.surfaceviewthread; 2 3 /* 4 * SurfaceView的示例程序 5 * 演示其流程 6 */ 7 8 import android.app.Activity; 9 import android.content.Context; 10 import android.graphics.Canvas; 11 import android.graphics.Color; 12 import android.graphics.Paint; 13 import android.graphics.RectF; 14 import android.os.Bundle; 15 import android.view.SurfaceHolder; 16 import android.view.SurfaceView; 17 18 public class MainActivity extends Activity { 19 20 public void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(new MyView(this)); 23 } 24 25 //内部类 26 class MyView extends SurfaceView implements SurfaceHolder.Callback{ 27 SurfaceHolder holder; 28 29 public MyView(Context context) { 30 super(context); 31 holder = this.getHolder();//获取holder 32 holder.addCallback(this); 33 //setFocusable(true); 34 } 35 36 @Override 37 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 38 39 } 40 41 @Override 42 public void surfaceCreated(SurfaceHolder holder) { 43 new Thread(new MyThread()).start(); 44 } 45 46 47 @Override 48 public void surfaceDestroyed(SurfaceHolder holder) { 49 } 50 51 //内部类的内部类 52 class MyThread implements Runnable{ 53 @Override 54 public void run() { 55 Canvas canvas = holder.lockCanvas(null);//获取画布 56 Paint mPaint = new Paint(); 57 mPaint.setColor(Color.BLUE); 58 canvas.drawRect(new RectF(40,60,80,80), mPaint); 59 holder.unlockCanvasAndPost(canvas);//解锁画布,提交画好的图像 60 } 61 } 62 } 63 }
代码写得简洁明了,学习起来非常方便,不多说。