如何加載圖片?
主要是通過BitmapFactory類提供方法加載圖片:
decodeFile:從文件系統中加載
decodeResource:從資源中加載
decodeStream:從輸入流中加載
decodeByteArray:從字節數組中加載
如何高效加載Bitmap?
采用BitmapFactory.Options來加載所需尺寸的圖片,可以按一定的采樣率來加載縮小的圖片,將縮小的圖片在ImageView中顯示。
具體實現流程:
a. 將BitmapFactory.Options中的inJustDecodeBounds參數設置為true并加載圖片
b. 從BitmapFactory.Options中獲取到圖片的原始寬高信息
c. 根據采樣率規則并結合目標view的所需大小計算出采樣率inSampleSize
d. 將BitmapFactory.Options的inJustDecodeBounds參數設為false,然后重新加載
注意:這里設置BitmapFactory.Options為true時,只會獲取到圖片的寬高信息,這樣的操作是輕量級的。
實現代碼:
/**
* 根據內部資源來壓縮圖片
* @param res 傳入的資源
* @param resId 傳入對應的id
* @param reqWidth 所需的寬度
* @param reqHeight 所需的高度
* @return
*/
public Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight){
final BitmapFactory.Options options = new BitmapFactory.Options();
//設置為true,表示只獲取圖片的尺寸
options.inJustDecodeBounds = true;
//計算壓縮比
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
//設置為false,表示獲取圖片的所有信息
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
if (reqHeight == 0 || reqWidth == 0)
return 1;
//獲取到圖片的原始寬高
final int width = options.outWidth;
final int height = options.outHeight;
int inSampleSize = 1;
//計算壓縮比,一般設置為1,2,4等2的次方數
if (height > reqHeight || width > reqWidth){
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth){
inSampleSize *= 2;
}
}
return inSampleSize;
}
調用方法:
imageView.setImageBitmap(decodeSampledBitmapResource(getResource(), R.id.image,100,100));