1 package com.example.administrator.mystudent.surfaceView; 2 3 import android.content.Context; 4 import android.graphics.Canvas; 5 import android.graphics.Color; 6 import android.graphics.Paint; 7 import android.graphics.Rect; 8 import android.view.SurfaceHolder; 9 import android.view.SurfaceView; 10 11 import com.example.administrator.mystudent.R; 12 13 14 /** 15 * Created by Administrator on 2016/9/13. 16 */ 17 public class TestSufaceView extends SurfaceView implements SurfaceHolder.Callback { 18 19 private SurfaceHolder holder; 20 private MyThread myThread; 21 22 public TestSufaceView(Context context) { 23 super(context); 24 holder = this.getHolder(); 25 holder.addCallback(this); 26 myThread = new MyThread(holder);//创建一个绘图线程 27 28 } 29 30 /** 31 * @param holder 在创建时激发,一般在这里调用画图的线程 32 */ 33 @Override 34 public void surfaceCreated(SurfaceHolder holder) { 35 36 myThread.isRun = true; 37 myThread.start(); 38 } 39 40 /** 41 * @param holder 42 * @param format 43 * @param width 44 * @param height 在surface的大小发生改变时激发 45 */ 46 @Override 47 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 48 49 } 50 51 /** 52 * @param holder 销毁时激发,一般在这里将画图的线程停止、释放 53 */ 54 @Override 55 public void surfaceDestroyed(SurfaceHolder holder) { 56 57 myThread.isRun = false; 58 } 59 60 //线程内部类 61 class MyThread extends Thread { 62 private SurfaceHolder holder; 63 public boolean isRun; 64 65 public MyThread(SurfaceHolder holder) { 66 this.holder = holder; 67 isRun = true; 68 } 69 70 @Override 71 public void run() { 72 73 int count = 0; 74 while (isRun) { 75 Canvas c = null; 76 try { 77 synchronized (holder) { 78 c = holder.lockCanvas();//锁定画布,一般在锁定后就可以通过其返回的画布对象Canvas,在其上面画图等操作了。 79 c.drawColor(Color.BLACK);//设置画布背景颜色 80 Paint p = new Paint(); //创建画笔 81 p.setColor(Color.WHITE); 82 Rect r = new Rect(100, 50, 300, 250); 83 c.drawRect(r, p); 84 c.drawText("这是第" + (count++) + "秒", 100, 310, p); 85 Thread.sleep(1000);//睡眠时间为1秒 86 } 87 } 88 catch(Exception e){ 89 e.printStackTrace(); 90 } finally 91 { 92 if (c != null) 93 { 94 holder.unlockCanvasAndPost(c);//结束锁定画图,并提交改变。 95 } 96 } 97 } 98 } 99 100 } 101 }