Android已經提供了View繪圖處理,View能夠知足大部分的繪圖場景,View經過刷新來重回視圖,android系統經過發出VSYNC信號進行視圖的重 繪,刷新間隔爲16ms,超過16ms,咱們可能就會感到卡頓了。對於邏輯太多,操做複雜的場景,頻繁的刷新界面,就會阻塞主線程,也會致使界面卡頓。
不少時候,咱們在自定義View的Log日誌看到這樣的警告java
Skipped 47 frames! The application may be doing too much work on it`s main thread.
這些告警就是由於在繪製過程當中,處理邏輯太多形成的。
爲了不這些問題的產生,Android系統提供了SurfaceView,SurfaceView是VIew的孿生兄弟,但它與View仍是有所不一樣的。android
SurfaceView的使用,要比View複雜,可是它也有一套模板來使用,大部分均可以嵌套這個模板進行使用。app
public class TempleSurfaceView extends SurfaceView implements SurfaceHolder.Callback,Runnable{}
實現SurfaceHolder.Callback接口,須要實現下面的方法:ide
//建立 @Override public void surfaceCreated(SurfaceHolder holder) { } //改變 @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } //銷燬 @Override public void surfaceDestroyed(SurfaceHolder holder) { }
實現Runnable接口,須要實現下面的方法:函數
@Override public void run() { //子線程 }
// SurfaceHolder private SurfaceHolder mHolder; // 用於繪圖的Canvas private Canvas mCanvas; // 子線程標誌位 private boolean mIsDrawing;
主要是初始化SurfaceHolder對象,並註冊SurfaceHolder 的回調方法。this
mHolder = getHolder(); mHolder.addCallback(this);
另外兩個,Canvas和標誌位。Canvas與View的onDraw()方法的Canvas同樣,用來進行繪圖,標誌位是用來控制線程的,SurfaceView是新起子線程來繪製的,而這個標誌位就是控制子線程的。線程
繪製的時候,通常都是利用三個回調方法進行操做。在surfaceCreated中開啓子線程繪製,而子線程用while (mIsDrawing)的循環來不停的繪製,在繪製中,經過lockCanvas()方法得到Canvas對象進行繪製,並經過unlockCanvasAndPost方法對畫布內容進行提交。
整個代碼3d
public class TempleSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Runnable { // SurfaceHolder private SurfaceHolder mHolder; // 用於繪圖的Canvas private Canvas mCanvas; // 子線程標誌位 private boolean mIsDrawing; public TempleSurfaceView(Context context) { super(context); initView(); } public TempleSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } public TempleSurfaceView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(); } private void initView() { mHolder = getHolder(); mHolder.addCallback(this); setFocusable(true); setFocusableInTouchMode(true); this.setKeepScreenOn(true); //mHolder.setFormat(PixelFormat.OPAQUE); } @Override public void surfaceCreated(SurfaceHolder holder) { mIsDrawing = true; new Thread(this).start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { mIsDrawing = false; } @Override public void run() { while (mIsDrawing) { draw(); } } private void draw() { try { mCanvas = mHolder.lockCanvas(); // draw sth } catch (Exception e) { } finally { if (mCanvas != null) mHolder.unlockCanvasAndPost(mCanvas); } } }
以上代碼知足大部分場景的SurfaceView繪圖需求,須要注意的是mHolder.unlockCanvasAndPost(mCanvas)方法放在finally 裏面,保證每次內容提交。
接下來,咱們看兩個實例,日誌
相似示波器,心電圖那個波紋一直在繪製的案例。固然View也能夠實現的,可是使用SurfaceView的好處,前面就已經說了。
要繪製一個cos函數,只須要不斷修改座標點,並知足cos函數,就能夠。使用Path對象來保存cos函數的座標點,在子線程中whiel循環中,不斷改變座標繪製就能夠了。
演示:自動繪製(這裏只展現圖片)
代碼code
package com.imooc.surfaceviewtest; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; public class CosView extends SurfaceView implements SurfaceHolder.Callback, Runnable { private SurfaceHolder mHolder; private Canvas mCanvas; private boolean mIsDrawing; private int x = 0; private int y = 0; private Path mPath; private Paint mPaint; public CosView(Context context) { super(context); initView(); } public CosView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } public CosView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(); } private void initView() { mHolder = getHolder(); mHolder.addCallback(this); setFocusable(true); setFocusableInTouchMode(true); this.setKeepScreenOn(true); mPath = new Path(); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setColor(Color.RED); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(10); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeJoin(Paint.Join.ROUND); } @Override public void surfaceCreated(SurfaceHolder holder) { mIsDrawing = true; mPath.moveTo(0, 400); new Thread(this).start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { mIsDrawing = false; } @Override public void run() { while (mIsDrawing) { draw(); x += 1; y = (int) (100*Math.cos(x * 2 * Math.PI / 180) + 400); mPath.lineTo(x, y); } } private void draw() { try { mCanvas = mHolder.lockCanvas(); // SurfaceView背景 mCanvas.drawColor(Color.WHITE); mCanvas.drawPath(mPath, mPaint); } catch (Exception e) { } finally { if (mCanvas != null) mHolder.unlockCanvasAndPost(mCanvas); } } }
這個案例是用SurfaceView實現一個簡單的繪圖板,繪圖的方法和View的同樣,經過Path對象來記錄手指滑動的路徑進行繪圖。在SurfaceView的onTouchEvent()中記錄Path路徑,代碼以下:
演示:手寫 王子豬
代碼
@Override public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mPath.moveTo(x, y); break; case MotionEvent.ACTION_MOVE: mPath.lineTo(x, y); break; case MotionEvent.ACTION_UP: break; } return true; }
在draw()方法中進行繪製,代碼以下:
private void draw() { try { mCanvas = mHolder.lockCanvas(); mCanvas.drawColor(Color.WHITE); mCanvas.drawPath(mPath, mPaint); } catch (Exception e) { } finally { if (mCanvas != null) mHolder.unlockCanvasAndPost(mCanvas); } }
咱們一直在不斷調用draw()方法,但有時候不須要這麼頻繁。因此,咱們能夠在子線程用sleep操做,節省資源,代碼以下:
@Override public void run() { long start = System.currentTimeMillis(); while (mIsDrawing) { draw(); } long end = System.currentTimeMillis(); // 50 - 100 if (end - start < 100) { try { Thread.sleep(100 - (end - start)); } catch (InterruptedException e) { e.printStackTrace(); } } }
經過draw()方法操做的時長來肯定sleep的時長,這是一個通用的解決方案,通常這個值在50~100之間。這篇文章只是SurfaceView的入門,其餘的用法,還有待開啓研究。
完整代碼以下:
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; public class SimpleDraw extends SurfaceView implements SurfaceHolder.Callback, Runnable { private SurfaceHolder mHolder; private Canvas mCanvas; private boolean mIsDrawing; private Path mPath; private Paint mPaint; public SimpleDraw(Context context) { super(context); initView(); } public SimpleDraw(Context context, AttributeSet attrs) { super(context, attrs); initView(); } public SimpleDraw(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(); } private void initView() { mHolder = getHolder(); mHolder.addCallback(this); setFocusable(true); setFocusableInTouchMode(true); this.setKeepScreenOn(true); mPath = new Path(); mPaint = new Paint(); mPaint.setColor(Color.RED); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(40); } @Override public void surfaceCreated(SurfaceHolder holder) { mIsDrawing = true; new Thread(this).start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { mIsDrawing = false; } @Override public void run() { long start = System.currentTimeMillis(); while (mIsDrawing) { draw(); } long end = System.currentTimeMillis(); // 50 - 100 if (end - start < 100) { try { Thread.sleep(100 - (end - start)); } catch (InterruptedException e) { e.printStackTrace(); } } } private void draw() { try { mCanvas = mHolder.lockCanvas(); mCanvas.drawColor(Color.WHITE); mCanvas.drawPath(mPath, mPaint); } catch (Exception e) { } finally { if (mCanvas != null) mHolder.unlockCanvasAndPost(mCanvas); } } @Override public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mPath.moveTo(x, y); break; case MotionEvent.ACTION_MOVE: mPath.lineTo(x, y); break; case MotionEvent.ACTION_UP: break; } return true; } }
歡迎關注公衆號 拖鞋王子豬 一塊兒開心起來。