当前位置: 动力学知识库 > 问答 > 编程问答 >

android - setDensity / setTargetDensity ignored when bitmap is drawn

问题描述:

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?\

网友答案:

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);
分享给朋友:
您可能感兴趣的文章:
随机阅读: