赞
踩
通过自定义View结合Touch事件,实现一个简单的画板功能!
实现思路
关键代码-自定义view画板
private void init() { //初始化画笔 paint = new Paint(); paint.setStrokeWidth(10); paint.setStyle(Paint.Style.STROKE); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //循环绘制所有路径 for (DrawPath path : paths) { //修改画笔的颜色和线宽 paint.setColor(path.getColor()); paint.setStrokeWidth(path.getLineWidth()); canvas.drawPath(path, paint); } } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //每次按下产生一个新的路径 DrawPath path = new DrawPath(); path.setColor(color); path.setLineWidth(lineWidth); path.moveTo(event.getX(), event.getY()); paths.add(path); invalidate(); break; case MotionEvent.ACTION_MOVE: //手指移动时,使用集合中最后一个路径添加线 if (paths.size() > 0) { paths.get(paths.size() - 1).lineTo(event.getX(), event.getY()); } invalidate(); break; case MotionEvent.ACTION_UP: break; } return true; }
关键代码-自定义path
import android.graphics.Path; /** * 其实就加了两个属性而已 * Created by Yhyu on 2017/2/21. */ public class DrawPath extends Path { private float lineWidth; private int color; public float getLineWidth() { return lineWidth; } public void setLineWidth(float lineWidth) { this.lineWidth = lineWidth; } public int getColor() { return color; } public void setColor(int color) { this.color = color; } }
结束语:实现方式千千万万,不要拘泥于某一种,既能实现功能,又能学到东西才是真的。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。