android 利用path 實現手寫板的手寫效果

南郭竽發表於2018-07-05

程式碼其實比較簡單,這種需求一般出現在相簿軟體裡面,可以讓使用者,觸控來在圖片上面寫字,畫圈圈之類的。反正就是記錄觸控軌跡吧。

public class TouchView extends View {

    private float currentX;
    private float currentY;
    private Paint paint;
    private Path path;


    public TouchView(Context context) {
        super(context);
    }

    public TouchView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TouchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public TouchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(getResources().getDimension(R.dimen.paint_width));
        paint.setStrokeCap(Paint.Cap.ROUND);
        path = new Path();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        currentX = event.getX();
        currentY = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                path.moveTo(currentX, currentY);
                break;
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                path.lineTo(currentX, currentY);
                break;
        }
        postInvalidate();
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawPath(path, paint);

    }
}

程式碼這就行了,比較簡單。效果類似下面這種:

不要在意圖片和大紅背景色

不要在意圖片和大紅背景色

需要注意的地方:

switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        path.moveTo(currentX, currentY); // 這裡是 moveTo
        break;
    case MotionEvent.ACTION_MOVE:
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_CANCEL:
        path.lineTo(currentX, currentY); // 這裡是 lineTo
        break;
}

沒有了。

相關文章