Reputation: 36351
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
Reputation: 16064
First, use stroke (not circles) to draw the line. Second, approximate. Here's a summary:
Paint
to use a stroke with width=5
. That reduces the need to draw so many circles.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.
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.
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
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.
Upvotes: 1