1. Introduction
(1) 有時用bitmap會發覺內存溢出導致error,主要是圖片太大才會發生此情況,以下code 可以解決內存溢出問題。
(2)目前android mobile device太多不同的節析度,此code 為了讓圖片可以依照節析度自行縮放。
2. Code
changePictureWH(讀取圖檔, 元件);//getResources().openRawResource(R.drawable.X), 元件
public void changePictureWH(InputStream resources, ImageButton id) {
Bitmap bmp;
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inJustDecodeBounds = true; //不分配空間
bmp = BitmapFactory.decodeStream(resources,null,bfo);
int picWidth = bfo.outWidth; //圖片寬度
int picHeight = bfo.outHeight; //圖片長度
int screenWidth = Define_Variable.scalWidth; //螢幕寬度
int screenHeight = Define_Variable.scalHeight; //螢幕長度
bfo.inSampleSize = 1; //isSampleSize 指圖片縮放程度 = 100/isSampleSize, 值越大圖越小
//根據螢幕的大小和圖片大小計算比例
if(picWidth > picHeight){
if(picWidth > screenWidth) bfo.inSampleSize = picWidth/screenWidth;
}else{
if(picHeight > screenHeight) bfo.inSampleSize = picHeight/screenHeight;
}
//產生經過縮放有像素的bitmap
bfo.inJustDecodeBounds = false; //從新分配空間
bmp = BitmapFactory.decodeStream(resources,null,bfo);
id.setImageBitmap(bmp);
}
沒有留言:
張貼留言