I am trying to composite a background bitmap from multiple smaller bitmaps. I am using Eclipse with the Android SDK.
I have loaded a (mostly) blank background bitmap (pixel dimensions are 320×480) like so:
Bitmap mBackground = BitmapFactory.decodeResource( res, R.drawable.background );
Then I load a bitmap ’tile’ (128×128) the same way.
I have tried multiple ways of drawing the tile onto the bitmap but every single method does not work the way I would like/expect. I want to draw the tile bitmap scaled down to 64×64 and at a specific location (pixel offset) on the background bitmap.
1) Using a Canvas…
Canvas c = new Canvas( mBackground );
c.drawBitmap( mTile, null, new Rect( 10, 10, 73, 73 ), null );
This draws the tile way too big (not fullsize, not 64×64, but somewhere in between, about 66% of original)
2) Using drawables (which basically seems to be the same):
Canvas c = new Canvas( mBackground );
c.translate( 10, 10 );
d.setBounds( 0, 0, 63, 63 );
d.draw( c );
Same result as experiment #1…
The documentation mentions in numerous places (without a concise explanation anywhere) that this has to do with the device independent ‘densities’ thus I tried the next approach…
3) Using fixed scale resources. I created the /res/drawable-nodpi (I also tried just /res/drawable) folder and moved my resources (background and tile png images) into it. That causes an exception when creating the Canvas from the background Bitmap because an unscaled bitmap apparently becomes immutable and therefore cannot be assigned to a Canvas!
4) I tried using BitmapFactory.Options and setting inScaled to false, and passing those options to both of the decodeResource calls for the background and the tile. This has the exact same effect as #3 (exception thrown).
Nothing has worked and its becoming quite frustrating. I am sure I am just missing some detail that is peculiar to bitmaps when it comes to the different coordinate spaces but I cannot find it anywhere in the documentation or elsewhere (I’ve tried multiple android development sites to no avail).
Hopefully someone who has done this will see this plea!
Thanks, jason
Canvas.drawBitmap()does not perform scaling afaik.Since your tile image is originally 128×128 and you want to draw it at 64×64, the simplest trick would be to call decodeResource() with the option to reduce it in size:
To do more powerful scaling (e.g. drawing your image at any size) you should wrap it in a
BitmapDrawable.