简体   繁体   中英

Animate a button as music plays

I want to implement a play/pause button which is filling up, as the music is played. My first try was to create a timer which fires at 20 FPS (every 50ms) and call View.invalidate() on my button. The button itself had a customer onDraw(...) method which would, only statically for now, draw a bitmap to the canvas.

However, then running this in the simulator (I use GenyMotion) I immediately noticed that the sounds is jiggling, as if the CPU couldn't handle it.

I am a beginner in Android, so before experimenting in different way I would like to know, what is the recommended approach to animate a button as the music plays?

  • Using a timer?
  • Somehow using an animation?
  • Can I speed up drawing? I will need to draw a masked and an unmasked bitmap, so these might be somehow CPU intense operations.

Suggestions I would like to give:

  • Always preload bitmaps/images before animation. Loading resources on the fly can affect performance.
  • Use Thread to perform operations.
  • The best way to handle the above 2, is to use SurfaceView
  • Handler is another way for performing timer tasks using handler.postDelayed()

There is a beautiful sample code from Android on "How to make simple native games using SurfaceView", using threads and pre-loading bitmaps, called LunarLander .

If you look at LunarView.java code, they are using thread named LunarThread which is created on constructor of LunarView and started with the surface is created .

It's inside the LunarThread they are performing all heavy task even drawing (inside thread's run method).

Basic OverView of LunarView:

  • On constructor, creates thread LunarThread , which preloads bitmaps and perform related tasks
  • When surface is created, starts the thread. Thread continuously runs/ gets paused, until the boolean flag mRun value is changed.
  • Inside run method, it gets the canvas from surfaceView, locks and draw everything onto canvas for that frame, and un-locks.
  • Its draws all time,till mRun value changed or when surface is destroyed(stops the thread, inside surfaceDestroyed(SurfaceHolder holder) method)

Use SurfaceView, you will see difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM