android学习笔记 SurfaceView模板

SurfaceView常用于需要频繁刷新,或者刷新时需要大量的数据处理。虽然,SurfaceView用法相对于View来说比较复杂,但是SufaceView使用时,有一套使用的模板代码,大部分SurfaceView绘图操作都可以套用这样的模板代码来编写。

代码如下:

/**
 * 
 * @author DunnLin
 * SurfaceView模板
 *
 */
public class SurfaceViewTemplate extends SurfaceView implements
		SurfaceHolder.Callback, Runnable {
	
	//SurfaceHolder
	private SurfaceHolder mHolder;
        //用于绘制的Canvas
	private Canvas mCanvas;
	//子线程标志位
	private boolean mIsDrawing;
	
	public SurfaceViewTemplate(Context context) {
		super(context);
		 initView();
	}

	public SurfaceViewTemplate(Context context, AttributeSet attrs) {
		super(context, attrs);
		 initView();
	}

	public SurfaceViewTemplate(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);
		
	}
	
	/**
	 * 通过子线程进行绘制
	 */
	@Override
	public void run() {
		
		while(mIsDrawing){
			draw();
		}
		
	}
	
	/**
	 * 进行绘制
	 */
	private void draw(){
		
		try{
			
			mCanvas = mHolder.lockCanvas();
			
		}catch(Exception e){
			
		}finally{
			
			if(mCanvas != null){
				mHolder.unlockCanvasAndPost(mCanvas);
			}
			
		}
	}

	/**
	 * SurfaceView的改变
	 */
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		
		
	}

	/**
	 * SurfaceView的创建
	 */
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		
		mIsDrawing = true;
		new Thread(this).start();
	}

	
	/**
	 * SurfaceView的销毁
	 */
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
	
		mIsDrawing = false;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值