Liazy
Liazy

Reputation: 301

Is canvas.save/restore or canvas.drawBitmap(Bitmap,Matrix,Paint) better?

Which is the difference between these two code snippets?

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image)
Matrix m = new Matrix();
m.postRotate(angle, bmp.getWidth()/2, bmp.getHeight()/2);
m.postTranslate(x,y);
canvas.drawBitmap(bmp,m,null);

Or:

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image)
canvas.save();
canvas.rotate(angle, bmp.getWidth()/2, bmp.getHeight()/2);
canvas.drawBitmap(bmp, x, y, null);
canvas.restore();

Is there a performance difference? Is it worth caching the Matrix in option 1 if I am trying to achieve a high framerate?

Upvotes: 0

Views: 1831

Answers (1)

CrackerJack9
CrackerJack9

Reputation: 3651

I am not sure why you are calling canvas.save() and canvas.restore() in only one of the examples, but I have done performance tests and show:

  • Using Matrix seems consistently faster (usually by 30-50%), for loading the same image.
  • However, some tests shows Canvas eventually was faster: after 300,000 tests - by 4-15%.

So if you need to load it a few times, use Matrix.
If you need to load it hundreds of thousands of times - you may be better off using only Canvas (or at least reusing the same Matrix instance).

Upvotes: 1

Related Questions