Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient 2D drawing in Android

I have searched for quite a few hours and have not been able to find a concise definite andswer to my question. I have an application where I need to draw a sports field (including all pitch lines) to the screen. So far, I have extended the SurfaceView and pretty much copied the rest of the LunarLander demo as well. All the data the application requires to draw the pitch to the correct dimensions is being received from a socket which works fine too. However, at the minute in the onDraw() function, I am drawing all lines each frame which is causing a fairly slow framerate in the emulator (e.g. ~10fps). Here is my onDraw() function:

@Override
public void onDraw(Canvas canvas) {
canvas.drawARGB(255,0,144,0);
canvas.drawLine(canvas, getFirstLine(), mPaint);
canvas.drawRect(canvas, getFirstRect(), mPaint);
canvas.drawRect(canvas, getSecondRect(), mPaint);
...
canvas.drawRect(canvas, getSecondRect(), mPaint);
drawAnimatedObjects();
}

I then draw circles and different positions over this background. My question is how do I make this more efficient? Is there a way that I can draw the lines at the application initialisation and not have to redraw them every frame?

Thanks for any help.

like image 268
Sonoman Avatar asked Aug 04 '10 15:08

Sonoman


1 Answers

You should definitely be caching any canvas drawing which will not change to a bitmap at initialization time and then draw that bitmap in onDraw(). That will help render times a lot. Something like:

Bitmap mField = null;

void init()
{
  mField = new Bitmap(...dimensions...);
  Canvas c = new Canvas(mField);
  c.drawRect(...);
  ...
}

void onDraw(Canvas c)
{
  c.drawBitmap(mField);
}
like image 163
Josh Avatar answered Sep 28 '22 01:09

Josh