概述
在開發(fā)時辛块,需要顯示顯示圖片的縮略圖一膨。使用 ThumbnailUtils.extractThumbnail 可以構(gòu)建縮略圖。
但是這個方法需要指定ImageView的寬度和高度,我們需要解決如何獲得寬度和高度的問題优构。
需求
我有個 imageView ,用于顯示圖片雁竞。
我使用 asyncTask獲得圖片钦椭,并準(zhǔn)備在這個imageView 中顯示該圖片的縮略圖,我準(zhǔn)備使用 ThumbnailUtils.extractThumbnail 方法生成縮略圖碑诉。
處理縮略圖的方法
ThumbnailUtils.extractThumbnail(source, width, height);
這個方法的參數(shù):
source 源文件(Bitmap類型)
width 壓縮成的寬度
height 壓縮成的高度
這里需要一個寬度和高度的參數(shù)玉凯,要想再imageView里填滿圖片的話,這里就應(yīng)該傳入imageView的寬度和高度联贩。
問題
我們在 activity的 onCreate漫仆,onStart方法,直接調(diào)用 imageView.getWidth 方法獲得寬度始終為0泪幌。
解決方法
使用步驟:
1.先獲得imageView 的 一個ViewTreeObserver 對象盲厌。
ViewTreeObserver vto2 = imageView1.getViewTreeObserver()
2.為這個 ViewTreeObserver 對象添加監(jiān)聽器,它需要一個 OnGlobalLayoutListener 類型的參數(shù) 。
vto2.addOnGlobalLayoutListener()
3.實現(xiàn)OnGlobalLayoutListener祸泪,在實現(xiàn)的方法里調(diào)用 imageView.getWidth 獲得寬度吗浩。
代碼
private void showImage(final File resultFileArg) {
if (resultFileArg != null && resultFileArg.exists()) {
// 添加下載圖片至 imageView
ViewTreeObserver vto2 = imageView1.getViewTreeObserver();
vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < 16) {
imageView1.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
imageView1.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
Bitmap bm = BitmapFactory.decodeFile(resultFileArg.getPath());
Bitmap thumbnailImg = ThumbnailUtils.extractThumbnail(bm,
imageView1.getMeasuredWidth(),
imageView1.getMeasuredHeight());
bm.recycle();
imageView1.setImageBitmap(thumbnailImg);
// imageView1.setImageBitmap(bm);
}
});
}
}