Search code examples
androidviewtouchsizepressure

How do I get android paint(stylus) size?


I am developing an App that need to detect the stylus's size, for instance, if I use my hand(relatively wide) to draw, return null, if I use the stylus(relatively small) to draw, execute draw.Point method.

I have no idea how to detect this. Please for help thanks.

My code list as below.

public PaintView(Context context) {
        super(context);
        paint=new Paint(Paint.DITHER_FLAG);
        bitmap = Bitmap.createBitmap(MainActivity.widthPixels, MainActivity.heightPixels, Bitmap.Config.ARGB_8888);
        canvas=new Canvas();
        canvas.setBitmap(bitmap);

        paint.setStyle(Paint.Style.STROKE);
        //float size = paint.getStrokeWidth();
        paint.setStrokeWidth(5);
        paint.setColor(Color.RED);
    }

@Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(bitmap,0,0,null);
    }

@Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction()==MotionEvent.ACTION_MOVE) {
            canvas.drawLine(mov_x, mov_y, event.getX(), event.getY(), paint);
            invalidate();
        }
        if (event.getAction()==MotionEvent.ACTION_DOWN) {
            mov_x=(int) event.getX();
            mov_y=(int) event.getY();
            canvas.drawPoint(mov_x, mov_y, paint);
            invalidate();
        }
        mov_x=(int) event.getX();
        mov_y=(int) event.getY();
        return true;
    }

Solution

  • You can use MotionEvent.getSize() method to detect sizes of finger and stylus touch and then create rule how to determine what caused the touch. Also MotionEvent.getPressure() may be useful.