如果無法找到目標設備的密度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