通過 getHolder()方法可以得到這個(gè) SurfaceHolder對(duì)象
發(fā)布時(shí)間:2013-9-17 16:07
發(fā)布者:
reggae
原理(來自Android的SDk文檔):
訪問SurfaceView的底層圖形是通過SurfaceHolder接口來實(shí)現(xiàn)的,通過 getHolder()方法可以得到這個(gè) SurfaceHolder對(duì)象。你應(yīng)該實(shí)現(xiàn)surfaceCreated(SurfaceHolder)和 surfaceDestroyed(SurfaceHolder)方法來知道在這個(gè)Surface在窗口的顯示和隱藏過程中是什么時(shí)候創(chuàng)建和銷毀的。
SurfaceView可以在多線程中被訪問。
注 意:一個(gè)SurfaceView只在SurfaceHolder.Callback.surfaceCreated() 和 SurfaceHolder.Callback.surfaceDestroyed()調(diào)用之間是可用的,其他時(shí)間是得不到它的Canvas對(duì)象的 (null)。
我的訪問過程:
創(chuàng)建一個(gè)SurfaceView的子類,實(shí)現(xiàn)SurfaceHolder.Callback接口。
得到這個(gè)SurfaceView的SurfaceHolder對(duì)象holder。
holder.addCallback(callback),也就是實(shí)現(xiàn)SurfaceHolder.Callback接口的類對(duì)象。
在SurfaceHolder.Callback.surfaceCreated()調(diào)用過后holder.lockCanvas()對(duì)象就可以得到SurfaceView對(duì)象對(duì)應(yīng)的Canvas對(duì)象canvas了。
用canvas對(duì)象畫圖。
畫圖結(jié)束后調(diào)用holder.unlockCanvasAndPost()就把圖畫在窗口中了。
SurfaceView可以多線程訪問,在多線程中畫圖。
- import android.content.Context;
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.graphics.Paint;
- import android.util.Log;
- import android.view.SurfaceHolder;
- import android.view.SurfaceView;
- public class MySurfaceView extends SurfaceView implements
- SurfaceHolder.Callback {
- private Context mContext;
- private SurfaceHolder mHolder;
- public TouchScreenAdjusterSurfaceView(Context context,) {
- super(context);
- mContext = context;
- mHolder = TouchScreenAdjusterSurfaceView.this.getHolder();
- mHolder.addCallback(TouchScreenAdjusterSurfaceView.this);
- this.setFocusableInTouchMode(true); // to make sure that we can get
- // touch events and key events,and
- // "setFocusable()" to make sure we
- // can get key events
- }
- @Override
- public void surfaceChanged(SurfaceHolder holder, int format, int width,
- int height) {
- // TODO Auto-generated method stub
- }
- @Override
- public void surfaceCreated(SurfaceHolder holder) {
- //now you can get the Canvas and draw something here
- }
- @Override
- public void surfaceDestroyed(SurfaceHolder holder) {
- // TODO Auto-generated method stub
- }
- public void drawMyShape(PointPostion ps) {
- mCanvas = mHolder.lockCanvas();
- // draw anything you like
- mHolder.unlockCanvasAndPost(mCanvas);
- }
- }
復(fù)制代碼 希望本文對(duì)廣大安卓開發(fā)者有所幫助,感謝閱讀本文。更多安卓技術(shù)問題歡迎加群探討:314230976,驗(yàn)證碼:eec,不寫驗(yàn)證不予通過喲~
|