ace
ace

Reputation: 12024

How to animate in Android Canvas?

I want to draw something at about 30 frames per seconds on Android Canvas or other convenient object for this purpose. In my application different graphic objects are drawn and if any of the graphic object is touched, the graphic object changes its shape. I looked at the onDraw(Canvas canvas) callback of View subclass but calling invalidate() does not help here: first I cannot control the frame rate and second if the objects are moving too fast, the motion appears jerky.

Upvotes: 0

Views: 3782

Answers (1)

Pat Briggs
Pat Briggs

Reputation: 131

I personally dislike Android's built-in Animation classes, so I tend to do all animations with Canvas by hand. I have found the most luck with creating a list of the images you want to use in your animation and then an int variable to store the current "frame" you are on. To advance the frame, I create a thread that sleeps for, say, 30 ms and then update the frame variable accordingly. Then in whatever update handler you are using, you can just create a switch statement or something of the like, and draw the respective frame.

It may seem like a lot of work, but it really isn't. Shove it all into a class and you will love yourself for many animations to come.

Upvotes: 1

Related Questions