Android: draw multiple bitmaps on another bitmap

I am trying to assemble a background bitmap from several smaller bitmaps. I am using Eclipse with the Android SDK.

I uploaded (mostly) an empty background bitmap (pixel sizes 320x480):

Bitmap mBackground = BitmapFactory.decodeResource( res, R.drawable.background ); 

Then I load the bitmap 'tile' (128x128) in the same way.

I tried several ways to draw tiles on a bitmap, but each individual method does not work as I would like / expect. I want to draw a tile bitmap reduced to 64x64 and in a specific place (pixel offset) on the background bitmap.

1) Using canvas ...

 Canvas c = new Canvas( mBackground ); c.drawBitmap( mTile, null, new Rect( 10, 10, 73, 73 ), null ); 

This draws the tile too large (not full, not 64x64, but somewhere in the middle, about 66% of the original)

2) Using drawables (basically this is the same thing):

 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 many places (without a brief explanation anywhere) that this is due to device-independent "densities", so I tried to make the following approach ...

3) Use of fixed-scale resources. I created the / res / drawable -nodpi folder (I also tried just / res / drawable) and moved my resources into it (background image and a fragment of png images). This throws an exception when creating a Canvas from a background bitmap, because the unscaled bitmap seems to become immutable and therefore cannot be bound to the Canvas!

4) I tried using BitmapFactory.Options and set inScaled to false and passed these parameters to both decodeResource calls for background and fragment. This has the same effect as # 3 (exception thrown).

Nothing worked, and it became rather unpleasant. I’m sure that I’m just missing some of the details specific to bitmaps when it comes to different coordinate spaces, but I can’t find them anywhere in the documentation or elsewhere (I tried several Android development sites without any benefit).

Hope someone who did this will see this request! Thanks Jason

+4
source share
2 answers

Canvas.drawBitmap() does not scale afaik.

Since your tile image initially has 128x128 and you want to draw it on 64x64, the easiest trick would be to call decodeResource () with the possibility of reducing its size:

 BitmapFactory.Options options = new BitmapFactory.Options() options.inSampleSize = 2; // downscale by 50% Bitmap mTile = BitmapFactory.decodeResource( res, R.drawable.tile, options ); 

To do more powerful scaling (for example, to draw an image of any size), you must wrap it in BitmapDrawable .

0
source

It looks like the density of your bitmaps is different ... There is a similar problem here . You should check the density of each downloaded Bitmap to see if there is the same problem.

0
source

Source: https://habr.com/ru/post/1339339/