如果无法找到目标设备的密度dpi,则从资源中拉出的图像会变大。例如,如果您使用的设备是DisplayMetrics.DENSITY_HIGH
(hdpi),但只有/res/drawable-mdpi
中的图像,那么当您通过类似getDrawable()
的方式检索到图像时,图像将自动按比例放大。
但是,对于下载的图像,系统不知道图像的设计密度,因为它不包含在指定密度的资源文件夹中,所以无法自动进行缩放。您必须使用BitmapFactory.Options
手动定义密度。考虑下面的函数:
/**
* Downloads an image for a specified density DPI.
* @param context the current application context
* @param url the url of the image to download
* @param imgDensity the density DPI the image is designed for (DisplayMetrics.DENSITY_MEDIUM, DisplayMetrics.DENSITY_HIGH, etc.)
* @return the downloaded image as a Bitmap
*/
public static Bitmap loadBitmap(Context context, String url, int imgDensity) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
BitmapFactory.Options options = new BitmapFactory.Options();
// This defines the density DPI the image is designed for.
options.inDensity = imgDensity;
// These define the density DPI you would like the image to be scaled to (if necessary).
options.inScreenDensity = metrics.densityDpi;
options.inTargetDensity = metrics.densityDpi;
try {
// Download image
InputStream is = new java.net.URL(url).openStream();
return BitmapFactory.decodeStream(is, null, options);
}
catch(Exception ex) {
// Handle error
}
return null;
}
所以,如果你在指定的URL图像被设计用于MDPI的屏幕,你会通过DisplayMetrics.DENSITY_MEDIUM
为imgDensity
参数。如果当前上下文具有更大的DPI密度(例如DisplayMetrics.DENSITY_HIGH
),则图像将相应地放大。
你的问题是什么?我假设你希望他们是86x86。您必须更改ImageView上的scaleType属性以便以适合您的方式为您缩放图像 – dymmeh 2012-03-05 17:09:41
问题是为什么在布局文件中设置的图像与下载和使用setImageBitmap或setImageDrawable设置的图像显示不同的大小,以及我可以如何确保所有图像都或多或少呈现相同的大小 – 2012-03-05 17:13:18