第1年10月11日 android canvas

1.

SurfaceView的使用
SurfaceView的使用,要比View复杂,但是它也有一套模板来使用,大部分都可以嵌套这个模板进行使用。

创建SurfaceView 创建自定义的SurfaceView继承SurfaceView,并实现两个接口,SurfaceHolder.Callback、Runnable

另外两个,Canvas和标志位。Canvas与View的onDraw()方法的Canvas一样,用来进行绘图,标志位是用来控制线程的,SurfaceView是新起子线程来绘制的,而这个标志位就是控制子线程的。

使用SurfaceView
通过SurfaceHolder 的lockCanvas(),就可以获取当前的Canvas绘图对象。注意一点,获取到的Canvas还是之前的Canvas对象,而不是一个新的。所以之前的绘图操作将被保留了,如果需要擦除,可以使用drawColor()来进行清理操作。
绘制的时候,一般都是利用三个回调方法进行操作。在surfaceCreated中开启子线程绘制,而子线程用while (mIsDrawing)的循环来不停的绘制,在绘制中,通过lockCanvas()方法获得Canvas对象进行绘制,并通过unlockCanvasAndPost方法对画布内容进行提交。

 

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);

		}

	}

}

  

 

https://blog.csdn.net/weixin_42626820/article/details/112138047

posted @ 2021-10-11 14:51  lianhuaren  阅读(44)  评论(0编辑  收藏  举报