Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setDensity / setTargetDensity ignored when bitmap is drawn

Tags:

android

bitmap

I have a Bitmap and I'm trying to use it as the tiled background for my window. The problem is the scale is wrong. I want to make the bitmap draw twice as large on screen. I've tried to use both Bitmap.setDensity and BitmapDrawable.setTargetDensity and both have no effect.

My code:

Bitmap bitmap = fromSomewhere();
int original_density = bitmap.getDensity(); // this returns 240
// bitmap.setDensity(..); // has no effect, tried with 120,160,480
BitmapDrawable drawable = new BitmapDrawable(bitmap);
// drawable.setTargetDensity(..); // has no effect, tried with 120,160,480
drawable.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
getWindow().setBackgroundDrawable(drawable);

Notes:

  • My target SDK is 8, I've also tried specifically setting <supports-screens android:anyDensity="true"/> in the manifest
  • The Bitmap object is given, I have no control over how it's generated, I can only make manipulations to it.
  • My test device is Samsung Galaxy 2 (high density), though I've also tested on the emulator on medium density and still no effects were seen.
  • I didn't change any other densities, specifically the one of getWindow()

Isn't density the simplest way to achieve a x2 scaling? Why isn't is working?\

like image 834
talkol Avatar asked May 21 '26 13:05

talkol


1 Answers

Not sure if this is an Android bug or by design. Struggled with this then finally ended up with the following workaround. The idea is you tile then apply a matrix transform to account for the pixel density. view being your ImageView

view.setScaleType(ImageView.ScaleType.MATRIX);

Matrix matrix = new Matrix();
float scaleFactor = view.getContext().getResources().getDisplayMetrics().density;
matrix.setScale(scaleFactor,scaleFactor);
view.setImageMatrix(matrix);

BitmapDrawable bitmapDrawable = new BitmapDrawable(view.getContext().getResources(), bitmap);
bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);

view.setImageDrawable(bitmapDrawable);
like image 190
atnmachine Avatar answered May 24 '26 03:05

atnmachine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!