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

}

实现效果图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值