SurfaceView的使用

SurfaceView一般应用在需要大量,及时的绘制图像的情境中。如游戏,照相机。

SurfaceView显示的内容实在子线程中进行绘制的,因此避免造成UI现成的阻塞。

[java]  view plain  copy
  1. class MySurfaceView extends SurfaceView implements Callback, Runnable {  
  2.     private SurfaceHolder mHolder;  
  3.     private Canvas mCanvas;  
  4.   
  5.     private Thread t;// 用户绘制的线程  
  6.     private boolean isRunning;  
  7.   
  8.     public MySurfaceView(Context context) {  
  9.         this(context, null);  
  10.     }  
  11.   
  12.     public MySurfaceView(Context context, AttributeSet attrs) {  
  13.         super(context, attrs);  
  14.   
  15.         mHolder = getHolder();// holder管理着SurfaceView的生命周期和绘制的Canvas  
  16.   
  17.         mHolder.addCallback(this);  
  18.         setFocusable(true);  
  19.         setFocusableInTouchMode(true);  
  20.         setKeepScreenOn(true);  
  21.     }  
  22.   
  23.     @Override  
  24.     public void run() {  
  25.   
  26.         // 不断进行绘制  
  27.         while (isRunning) {  
  28.             draw();  
  29.         }  
  30.     }  
  31.   
  32.     private void draw() {  
  33.         // 当点击home键或者back键的时候,surfaceView会被销毁,而当surfaceview被销毁后,用于绘制的子线程可能还在运行进行绘制,可能会抛些什么异常  
  34.         // 所以要进行try  
  35.         try {  
  36.             mCanvas = mHolder.lockCanvas();  
  37.             if (mCanvas != null) {  
  38.   
  39.                 if (mCanvas != null) {  
  40.                     // TODO draw something  
  41.                 }  
  42.             }  
  43.         } catch (Exception e) {  
  44.         } finally {  
  45.             if (mCanvas != null) {  
  46.                 mHolder.unlockCanvasAndPost(mCanvas);  
  47.             }  
  48.         }  
  49.     }  
  50.   
  51.     @Override  
  52.     public void surfaceCreated(SurfaceHolder holder) {  
  53.         isRunning = true;  
  54.         t = new Thread(this);  
  55.         t.start();  
  56.     }  
  57.   
  58.     @Override  
  59.     public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {  
  60.   
  61.     }  
  62.   
  63.     @Override  
  64.     public void surfaceDestroyed(SurfaceHolder holder) {  
  65.         isRunning = false;  
  66.   
  67.     }  
  68. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值