Reputation: 1565
I'm building a game using Android 2.2. The main game Activity
uses a custom SurfaceView
:
class GameView extends SurfaceView
From what I understand, the onDraw()
method requires its own Thread to be executed. That in mind, I am planning to add a background image in onDraw()
:
canvas.drawBitmap(wallpaper, 0, 0, paint);
paint = new Paint();
But when I execute the game, it becomes very slow. If I comment out the new Paint()
line, the game speeds up.
Is there something I am doing wrong, or is there a solution to my problem? For example, is there a way to reduce the number of calls to onDraw()
? Or add an XML
attribute to my custom SurfaceView
class?
Here's the code how I load the drawable images.
public Bitmap loadBitmap(String image) {
Bitmap bitmap = null;
try {
int id = R.drawable.class.getField(image).getInt(new Integer(0));
bitmap = BitmapFactory.decodeResource(context.getResources(), id);
// bitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.RGB_565);
} catch(Exception ex) {
Log.e("loadBitmap", ex.getMessage());
}
return bitmap;
}
Here's the code of the onDraw
method.
Unfortunately, I can't post everything.
paint.setColor(Color.BLACK);
canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
canvas.drawBitmap(gameLevel.getBitmap(), 0, 0, paint);
// draw object(1) 320x25
// draw object(5) 50x50 each
// draw object(n) 15x15 each, estimate
// draw object(n) 50x50 each
// collision check, draw hit tile on the image sheet
// draw game information using canvas.drawText() timeLine++;
Thanks in advance!
Upvotes: 4
Views: 5513
Reputation: 544
If the problem is only the "paint = new Paint();" line, why don't you create the Paint object only once? When the class is first created and make it a Class variable. Then just use the object everytime you want.
Upvotes: 3
Reputation: 15108
You could try to load the background as RGB_565 instead of ARGB_8888 in case you haven't already. Otherwise there is not much you can do except switching to OpenGL
EDIT:
Options options = new Options();
options.inDither = false;
options.inJustDecodeBounds = false;
options.inSampleSize = 1;
options.mCancel = false;
options.inPreferredConfig = Config.RGB_565;
bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);
If that doesn't help other reasons may be:
Upvotes: 1