I am using SurfaceView to draw a lot of Bitmaps onto canvas. This causes really variable frame rates depending on how many objects are present. My code below:

public class OriginalView extends SurfaceView implements SurfaceHolder.Callback {
  private final static int THREAD_SLEEP_TIME = 32;
  private DrawThread drawthread;

  private onDraw(Canvas canvas);
  public void onSizeChanged(int w, int h, int oldW, int oldH);
  public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height);
  public void surfaceCreated(SurfaceHolder holder);
  public void surfaceDestroyed(SurfaceHolder holder);

  private DrawThread extends Thread {
    private SurfaceHolder surfaceHolder;
    public boolean threadIsRunning;
    public DrawThread (SurfaceHolder holder) {
      threadIsRunning = true;
      surfaceHolder = holder;
    public void run() {
      Canvas canvas = null;
      while(threadIsRunning) {
        try {
          canvas = surfaceHolder.lockCanvas(null);
          synchronized (surfaceHolder) {
            if (canvas!=null) onDraw(canvas);


        } catch (InterruptedException e) {
        } finally {
          if (canvas != null) surfaceHolder.unlockCanvasAndPost(canvas);

As you can see here in DrawThread's run function that the Thread is supposed to sleep for a constant value of time, predefined here as 32 milliseconds, but since sometimes onDraw(canvas) takes more time, varied due to number of components on screen, the frame rate per second that this code achieve is 17 - 51 fps in my game. This is highly unacceptable. How can I draw lots of Bitmaps onto a canvas, while maintaining high frame rates?

  • \$\begingroup\$ The correct way to do this is to post the question and answer separately. If you could please edit the question to remove the answer, then post the answer below that would be appreciated. I know you have a waiting period, so after that time is fine. Thanks for sharing! \$\endgroup\$ – MichaelHouse Aug 6 '13 at 22:25
  • \$\begingroup\$ I'll just do that in my next post. Thanks for the suggestion. I'm still new to the site. \$\endgroup\$ – Aekasitt Guruvanich Aug 12 '13 at 15:27
  • \$\begingroup\$ I removed the answer for you, feel free to add it as an answer below. \$\endgroup\$ – MichaelHouse Aug 12 '13 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.