0

I am trying to perform basic task of rotating a canvas 20 times a second using timer but it doesn't seem to be working properly and its lagging. for example, if I rotate rectangle 0.3 degrees per 50 ms it should rotate 6 degree in on second, but that is not the case. It really slow in rotation. Here is my sample code:

//Code for update task
class UpdateTimeTask extends TimerTask {

      public void run() {
              hndView.post(new Runnable() {
                   public void run() {
                           hndView.invalidate(); //this code invalidates custom view that calls onDraw to draw rotated hand
                   }
                 });
      }
}


//Code for onDraw method of custom view that needs to be update
@Override 
protected void onDraw(Canvas canvas){

    super.onDraw(canvas);

    //ang is angle to rotate and inc is float value of 0.3 degree to be incremented
    ang = ang + inc;
    if (ang >= 360) ang = ang - 360;
    canvas.rotate(ang, canvas.getWidth()/2, canvas.getHeight()/2);  
    canvas.drawRect((canvas.getWidth()/2 - 2), (canvas.getHeight()/2 - 125), (canvas.getWidth()/2 + 2), (canvas.getHeight()/2 + 10), mTextPaint);
    canvas.restore();

}

//code to schedule task
Timer timer = new Timer();
UpdateTimeTask tt = new UpdateTimeTask();
timer.schedule(tt, 0, 50);

Can anyone please tell me what am I doing wrong here? Should I used different approach to perform this task? Because its hard to believe that you cannot have simple smooth rotation of rectangle 20 times in one second.

dave.c
  • 10,910
  • 5
  • 39
  • 62
Parashar
  • 85
  • 1
  • 8

3 Answers3

2

Timer/TimerTask are not supposed to be precise and are not supposed to be used for this purpose. Follow the recipes for 2D game development, such as the LunarLander sample that is included in your SDK. Or, you could just search StackOverflow and find all sorts of useful posts on the subject.

Community
  • 1
  • 1
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
1

I believe you are not using a SurfaceView.

Drawing like that to a canvas was meant for controls and not fast rendering(read >10fps)

If you want performance you need either to use a SurfaceView where you'll average a 25-30 fps or opengl

Please read : http://developer.android.com/guide/topics/graphics/index.html

Yahel
  • 8,522
  • 2
  • 24
  • 32
0

The number of calls to invalidate need not equal the number of calls to onDraw. If your timer ends up running twice successively before the UI thread gets a chance to run, then the double invalidate will end up only causing a single rotation. Consider putting in debug code to validate the number of calls to those two methods.

Yuliy
  • 17,381
  • 6
  • 41
  • 47