Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android drawing a line to follow your finger

What I want to do is to draw a line that will follow my finger. I've created a custom view, and I have an onTouchEvent() that works.

I can draw a static line in the onDraw() method without much trouble.

I'm not really sure how to get the line to draw as my finger moves though.

  public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            Log.e(TAG, " - DOWN -");
            Log.e(TAG, " getX: " + event.getX());
            break;
        }
        case MotionEvent.ACTION_UP: {
            Log.e(TAG, " - UP -");
            Log.e(TAG, " getX: " + event.getX());
            break;
        }
        }
        return true;
    }

Any hints you guys who have been doing it a while can give?

Do I need to set coordinates on the onTouchEvent() and constantly invalidate the view so the little line segments draw?

In the end I just want to be able to basically doodle on the screen using my finger for this experiment.

like image 204
jacklin Avatar asked Nov 29 '10 02:11

jacklin


People also ask

How do you draw a straight line on android?

quadTo(mX, mY, (x + mX)/2, (y + mY)/2); You will be able to draw straight lines.

What is Android path?

android.graphics.Path. The Path class encapsulates compound (multiple contour) geometric paths consisting of straight line segments, quadratic curves, and cubic curves. It can be drawn with canvas.


1 Answers

You're only tracking the up and down events. Track the ACTION_MOVE event too. Beware that it will track continuously, even if the person's finger isn't apparently moving. Your code should go something like this:

ACTION_DOWN: Store position.

ACTION_MOVE: If position is different from stored position then draw a line from stored position to current position, and update stored position to current.

ACTION_UP: Stop.

In the ACTION_MOVE bit, it might be a good idea to check if the position is at least 2 or 3 pixels away from the stored position. If you're going to store all of the plot points, so you can do something with the data later, then maybe increase that to 10 pixels so you don't end up with hundreds of points for a simple line.

like image 160
Andrew Smith Avatar answered Sep 24 '22 19:09

Andrew Smith