Android趣味小实例—涂鸦画板

自己写了一个涂鸦画板,直接上源码,网上的资源很多,但是需要注意:很多网上资源代码里设置的是drawLine,个人感觉drawPath效果更佳,源码如下:

public class MainActivity extends Activity implements OnTouchListener {

SurfaceView mSurfaceView=null;
SurfaceHolder mSurfaceHolder=null;
Button cleanButton=null;
Button colorButton=null;
private Paint mPaint=null;
private Path  mPath=null;
private Random random=new Random();
private Canvas mCanvas;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSurfaceView=(SurfaceView) findViewById(R.id.surfaceview);
mSurfaceView.setOnTouchListener(this);
//创建SurfaceHolder对象
mSurfaceHolder=mSurfaceView.getHolder();
setPaint();
cleanButton=(Button) findViewById(R.id.flushbutton);
//添加清屏按钮监听
cleanButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPath.reset();
setCanvas();
}
});
}
private void setPaint() {
//创建画笔对象
mPaint=new Paint();
mPath=new Path();
//设置画笔颜色随机
mPaint.setARGB(255,random.nextInt(255),random.nextInt(255),random.nextInt(255));
//设置画笔去锯齿
mPaint.setAntiAlias(true);
//设置画笔空心
mPaint.setStyle(Style.STROKE);
//画笔的粗细
mPaint.setStrokeWidth(3.0f);
}
public boolean onTouch(View v, MotionEvent event) {
//获得x坐标
float x=event.getX();
//获得y坐标
float y=event.getY();
//获得触屏事件
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
mPath.moveTo(x, y);
setCanvas();break;
//如果是拖动事件
case MotionEvent.ACTION_MOVE:{
mPath.lineTo(x, y);
setCanvas();break;
}}
return true;
}
private void setCanvas() {
//锁定整个SurfaceView
mCanvas = mSurfaceHolder.lockCanvas();
mCanvas.drawColor(Color.BLACK);
//绘制完成,提交修改
mCanvas.drawPath(mPath, mPaint);
mSurfaceHolder.unlockCanvasAndPost(mCanvas);
}

}

实现效果图:

Android趣味小实例—涂鸦画板_第1张图片

你可能感兴趣的:(Android趣味小实例—涂鸦画板)