我需要将头像添加到网格项目。如何调整图像大小以适应多个屏幕密度
我想知道如何处理从手机库中选择的图像的大小调整。一旦选定,我想会需要一些调整大小,以适应网格。
但是,我是否需要为每个屏幕密度存储调整大小的图像;存储一个xhdpi版本并缩小其他设备的尺寸,或以其他方式变得聪明?
原因是,应用程序将此图像存储到云数据库和其他人可以下载此图像。他们可能会在不同的设备上看到图像(因此需要不同的图像尺寸)。该图像的管理应如何处理?
我需要将头像添加到网格项目。如何调整图像大小以适应多个屏幕密度
我想知道如何处理从手机库中选择的图像的大小调整。一旦选定,我想会需要一些调整大小,以适应网格。
但是,我是否需要为每个屏幕密度存储调整大小的图像;存储一个xhdpi版本并缩小其他设备的尺寸,或以其他方式变得聪明?
原因是,应用程序将此图像存储到云数据库和其他人可以下载此图像。他们可能会在不同的设备上看到图像(因此需要不同的图像尺寸)。该图像的管理应如何处理?
我希望你找到下面的代码有用。它将以最小的开销返回具有所需维度的图像。我用过这么多次,像魅力一样。您可以根据目标设备设置所需的尺寸。缩放会导致图片模糊,但这不会。
private Bitmap getBitmap(Uri uri) {
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 200000; // 0.2MP
in = my_context.getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true; //request only the dimesion
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1/Math.pow(scale, 2)) > IMAGE_MAX_SIZE) {
scale++;
}
Bitmap b = null;
in = my_context.getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
double y = Math.sqrt(IMAGE_MAX_SIZE
/(((double) width)/height));
double x = (y/height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x, (int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
return b;
} catch (IOException e) {
return null;
}
}
android:scaleType="fitXY"
android:layout_gravity="center"
将缩放的图像和中心它的尺寸大小与以FILL_PARENT一个容器,它应该做到这一点。
有趣的感谢。看起来我可以保存我需要的最大尺寸的图像,并使用它来管理它的适合性。 – HGPB
你可以把你的图像绘制(无需创建xhdpi,hdpi,mdpi,ldpi ...)(全局图像)。
然后,您可以为不同的屏幕尺寸创建4个相同的布局。您的所有布局都可以使用可绘制导演中的图像。所以你可以轻松地调整你的图像。
做这样的事情:
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);
谢谢,我会认为这是一个调整大小的选项。 – HGPB