Android将图像缩放到屏幕密度

use*_*344 14 android image android-layout

我有一个应用程序,嵌入式可绘制48x48像素,71,12像素/英寸我通过流加载相同的图像到网络服务器,然后加载该流

return new BitmapDrawable(getActivity().getResources(), new ByteArrayInputStream(imageThumbnail));
Run Code Online (Sandbox Code Playgroud)

显示的结果是:

截图

我怎样才能使BitmapDrawable与其他drawable一样扩展?

小智 16

你可以触发android bitmapfactory自动缩放位图,代码为:

BitmapFactory.Options options = new BitmapFactory.Options();
DisplayMetrics metrics = context.getApplicationContext().getResources().getDisplayMetrics();
options.inScreenDensity = metrics.densityDpi;
options.inTargetDensity =  metrics.densityDpi;
options.inDensity = DisplayMetrics.DENSITY_DEFAULT;

Bitmap bm = BitmapFactory.decodeStream(in, null, options);
in.close();
BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(), bm);
Run Code Online (Sandbox Code Playgroud)

  • 这个答案需要解释使用 `inScreenDensity`、`inTargetDensity` 和 `inDensity`。 (2认同)

Sno*_*cks 11

做这样的事情:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

Bitmap bitmapOrg = new BitmapDrawable(getResources(), new  ByteArrayInputStream(imageThumbnail)).getBitmap();

int width = bitmapOrg.getWidth();
int height = bitmapOrg.getHeight();

float scaleWidth = metrics.scaledDensity;
float scaleHeight = metrics.scaledDensity;

// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);

// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height, matrix, true);
Run Code Online (Sandbox Code Playgroud)

要么

也许尝试一种不同的方法...尝试在dip布局中设置图像的高度和宽度,我猜你现在有了带有wrap_content高度和宽度的ImageView,尝试将高度和宽度设置为48dip

  • 也许尝试一种不同的方法...尝试在XML布局中设置图像的高度和宽度,我猜你现在有了带有wrap_content高度和宽度的ImageView,尝试将高度和宽度设置为48dip (2认同)