当绘制位图时,setDensity / setTargetDensity被忽略。

3
我有一个位图(Bitmap),我想将其用作窗口的平铺背景。问题是比例不对。我希望在屏幕上将位图放大两倍。我尝试使用 Bitmap.setDensity 和 BitmapDrawable.setTargetDensity 两种方法,但都没有效果。
我的代码:
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);

注意事项:

  • 我的目标SDK是8,我也尝试在清单中明确设置<supports-screens android:anyDensity="true"/>
  • Bitmap对象已经给定,我无法控制它是如何生成的,我只能对其进行调整。
  • 我的测试设备是三星Galaxy 2(高密度),尽管我也在模拟器上测试了中密度,但仍然没有效果。
  • 我没有改变任何其他密度,特别是getWindow()的密度。

密度不是实现x2缩放的最简单方法吗?为什么不起作用?


1
我仍然不知道解决方案,但我有同样的问题,并且我意识到当您设置平铺模式时,密度设置被忽略了。 - Kamen Goranchev
当设置瓷砖模式时,同意忽略密度。同时,当设置TileMode时,ImageView的StretchMode.FIT_XY也会被忽略。 - Moritz
1个回答

1

不确定这是 Android 的 bug 还是设计如此。我曾经为此苦苦挣扎,最终采用了以下解决方法。思路是先平铺,然后应用矩阵变换来考虑像素密度。 view 是你的 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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接