自定義View練習 - 手寫闆
練習來源
自定義控件-使用Canvas繪圖定義一個手寫闆
效果圖
主要代碼
WriteView.java
public class WriteView extends View {
//畫筆
private Paint paint;
//使用者觸摸的路徑
private Path path;
public WriteView(Context context) {
this(context, null);
}
public WriteView(Context context, AttributeSet attrs) {
this(context, attrs, );
}
public WriteView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true); //抗鋸齒
paint.setDither(true); //防抖動
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);//設定畫筆連接配接處圓潤
paint.setStrokeWidth(f);//畫筆大小
path = new Path();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(x,y);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(x,y);
break;
case MotionEvent.ACTION_UP:
break;
}
postInvalidate();//重繪
return false;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path,paint); //繪制路徑
}
/**
* 清空路徑
*/
public void reset(){
path.reset();
postInvalidate();
}
}
學習知識
- 将使用者Touch的軌迹存儲到Path中. 使用drawPath()來實時繪制.
- 調用postInvalidate()會進而一步一步的調用的View#onDraw().
- 在View#onTouchEvent()中MotionEvent.Action_DOWN事件中一定要傳回true, 表示接下來的Move,Up事件都有目前View來消費.
- 清空畫布,隻需将path清空,重新繪制即可.
- 使用AndroidStudio快速生成自定義View的構造方法的快捷輸入為ViewConstructors.
github: https://github.com/cizkey/CustomPractice/tree/master/WriteView