Monday, November 11, 2013

Using Bitmap to store canvas paint to optimize UI fluency in Android

This week, I was writing an android program where I have an ImageView that is being updated very frequently. The MVC pattern is used there. Basically, I have a model that stores the location and color of many circles and the ImageView will repaint each of them on its onDraw method, which looks like this: Unfortunately, this scales badly and gets really slow when the circle list in the model gets large. The key to a better solution is that the model only changes a little each time in most cases. In my case, I am removing one circle and adding 4 new circles each time. A better solution will be creating a Bitmap and store it either in the model or the view, so that it is regularly updated when the model changes. Each time the model is changed, we only need to erase one circle and draw another 4 on this Bitmap. For the ImageView, the onDraw method simply load the bitmap, which internally is just a memcpy and takes only a few millisecond. In other words, you don't redraw what is not changed. Finally, you can draw circle on the Bitmap easily by first create a Canvas onto it then draws on the Canvas in exactly the same way you normally do in an onDraw method. The following code snippet is what I used in my program. When I create a Bitmap: When the model changes: This will modify the underlying Bitmap. Of course, the Bitmap must be mutable.

No comments:

Post a Comment