我想縮放現有的位圖。因此,我使用Bitmap.createBitmap(位圖b,int x,int y,int width,int height,Matrix m,布爾過濾器)來創建縮放位圖。如果Matrix對象的縮放比例小於1,則此方法運行良好。但是,如果比率等於或大於1,該方法將返回一個位圖,其中包含我希望的寬度和高度,但沒有圖像(透明)。我想知道爲什麼以及如何解決這個問題。createBitmap()返回一個未繪製的位圖
Bitmap imageBitmap;
imageBitmap = weiboView.getDrawingCache();
Log.d("cosmo", "bitmap generated: "+imageBitmap.getWidth()+" * "+imageBitmap.getHeight());
//Init and configure and load the image view
ImageView imageView = new ImageView(this);
imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
imageView.setScaleType(ScaleType.FIT_CENTER);
containerLayout.addView(imageView);
//create a scaled bitmap to assign to the image view
Bitmap scaledImageBitmap = MyBitmapUtils.getBitmapScaledToFitWidth(getWindowManager().getDefaultDisplay().getWidth(), imageBitmap);
Log.d("cosmo", "scaled: "+scaledImageBitmap.getWidth()+" * "+scaledImageBitmap.getHeight());
//Here if I set imageBitmap as the image of imageView it works well
imageView.setImageBitmap(scaledImageBitmap);
這裏是MyBitmapUtils.getBitmapScaledToFitWidth:
public static Bitmap getBitmapScaledToFitWidth(int targetWidth, Bitmap bitmap) {
float ratio = (float)targetWidth/(float)bitmap.getWidth();
Log.d("cosmo", "ratio is "+ratio);
//ratio = 0.5f;
Matrix matrix = new Matrix();
matrix.postScale(ratio, ratio);
Bitmap target = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,false);
return target;
}
我知道這是怎麼回事。這是因爲該圖像的高度大於2048,並在Android的系統創建一個大於2048 * 2048位圖將導致OOM(我的logcat沒有報告這個錯誤,奇怪)
,爲什麼你需要縮放的位圖?你想把它保存在SD卡上還是發送到某個地方? – pskink
只是想縮放它以適應指定寬度的圖像視圖 – cosmozhang
不,不,不要這樣做,使用scaleType =「matrix」並調用setImageMatrix,或者使用任何其他長寬比來保持scaleType – pskink