Get Off My Lawn
Get Off My Lawn

Reputation: 36351

Drawing with your fingers

I found this little sample code, to do drawing with your finger:
http://marakana.com/tutorials/android/2d-graphics-example.html

Here is some of the relevant code:

List<Point> points = new ArrayList<Point>();

@Override
public void onDraw(Canvas canvas) {
    for (Point point : points) {
        canvas.drawCircle(point.x, point.y, 5, paint);
    }
}

public boolean onTouch(View view, MotionEvent event) {
    Point point = new Point();
    point.x = event.getX();
    point.y = event.getY();
    points.add(point);
    invalidate();
    Log.d(TAG, "point: " + point);
    return true;
}

I was looking through it, and saw that they are adding points to an ArrayList, then looping through the ArrayList, this doesn't seem like it is a very optimized approach to this. Is there a better approach or is this a good approach?

After testing on my Samsung GS3, I colored the whole screen in with a circle size of 20, and the closer it got to full color the slower it took to draw, and then circles were becoming spaced out.

Upvotes: 4

Views: 424

Answers (2)

andr
andr

Reputation: 16064

First, use stroke (not circles) to draw the line. Second, approximate. Here's a summary:

  1. Change Paint to use a stroke with width=5. That reduces the need to draw so many circles.
  2. Pick a threshold, for example 3px after which you'll add a point in onTouch().

    if (Math.abs(previousX - event.getX()) < THRESHOLD
            && Math.abs(previousY - event.getY()) < THRESHOLD) {
        return;
    }
    previousX = event.getX();
    previousY = event.getY();
    // drawing update goes here
    

    This should reduce number of (unnoticeable) points.

  3. Use Picture or Path class to draw the line to, and use Canvas.drawPath() or Canvas.drawPicture(). This, especially for large number of points, will really speed the drawing since all drawing commands will be passed to the internal drawing function in one call.

  4. Simplify the shape at need. For example, you could delete eldest points (which would be a perfect case to use circular buffer), use the Ramer-Douglas-Peucker algorithm which is pretty easy to implement, gives good results and has complexity of O(nlogn).

Upvotes: 1

IluTov
IluTov

Reputation: 6862

No, this makes sense in this example.

He loops through all the points he wants to draw. This means he adds every point to the array, so he can loop through all the objects at once.

You'll often see this in game programming.


This is also very expandable.

  1. You can add as many points as you want
  2. It supports polymorphism
  3. You don't have to make variables for multiple points > Less code

Upvotes: 1

Related Questions