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