欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  技术分享

Android自定义SurfaceView实现画板源码下载

程序员文章站 2022-03-01 14:48:56
...

最近写了一个Android画板功能的简单实现例子、通过继承SurfaceView的一个自定义View来实现的、实现方法也比较简单、以下是效果图

Android自定义SurfaceView实现画板源码下载


MySurfaceView代码

public class MyView extends SurfaceView 
		implements Callback,OnTouchListener{

	private Paint p = new Paint();
	private Path path = new Path();
	
	public MyView(Context context, AttributeSet attrs) {
		super(context, attrs);
		getHolder().addCallback(this);
		p.setColor(Color.RED);
		p.setTextSize(10);
		p.setAntiAlias(true);
		p.setStyle(Style.STROKE);
		setOnTouchListener(this);
		
	}
	public void draw(){
		Canvas canvas = getHolder().lockCanvas();
		canvas.drawColor(Color.WHITE);
		canvas.drawPath(path, p);
		getHolder().unlockCanvasAndPost(canvas);
	}
	
	
	public void clear(){
		path.reset();
		draw();
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		draw();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, 
		int format, int width, int height) {
		
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		
	}
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			path.moveTo(event.getX(), event.getY());
			draw();
			break;

		case MotionEvent.ACTION_MOVE:
			path.lineTo(event.getX(), event.getY());
			draw();
			break;
		}
		
		return true;
	}

}

最后给大家贴上例子的源代码、大家可以下载看看、集成到自己的项目中去哈

源代码下载链接: http://dwtedx.com/download.html?bdkey=s/1o6iHZWu 密码: o1ln