2010-07-06 133 views
0

我正在寫一個音樂應用程序,我已經得到了專輯的藝術。然而,他們出現了各種規模。那麼,我如何標準化返回的位圖的大小呢?調整位圖大小

回答

4

你會做這樣的事情:

// load the origial BitMap (500 x 500 px) 
     Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), 
       R.drawable.android); 

     int width = bitmapOrg.width(); 
     int height = bitmapOrg.height(); 
     int newWidth = 200; 
     int newHeight = 200; 

     // calculate the scale - in this case = 0.4f 
     float scaleWidth = ((float) newWidth)/width; 
     float scaleHeight = ((float) newHeight)/height; 

     // createa matrix for the manipulation 
     Matrix matrix = new Matrix(); 
     // resize the bit map 
     matrix.postScale(scaleWidth, scaleHeight); 

     // recreate the new Bitmap 
     Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, 
          width, height, matrix, true); 
0

或者當你畫在畫布上,你可以縮放位圖到所需的大小:

從Android文檔:

drawBitmap(位圖位圖,Rect src,Rect dst,Paint paint) 繪製指定的位圖,自動縮放/翻譯以填充目標矩形。

讓src成爲空和DST是一個矩形的大小/位置,你希望它在畫布上,建立像

Rect rect = new Rect(0, 0, width, height) 
canvas.drawBitmap(bitmap, null, rect) 
0

在我的經驗中接受的答案代碼不起作用,至少在一些平臺上。

Bitmap.createBitmap(bitmapOrg, 0, 0, width, height, matrix, true); 

會給你一個原始的全尺寸下采樣圖像 - 所以只是一個模糊的圖像。

有趣的是,代碼

Bitmap resizedBitmap = Bitmap.createScaledBitmap(square, (int) targetWidth, (int) targetHeight, false); 

也給出了模糊的圖像。在我的情況下有必要這樣做:

// RESIZE THE BIT MAP 

// According to a variety of resources, this function should give us pixels from the dp of the screen 
// From http://stackoverflow.com/questions/4605527/converting-pixels-to-dp-in-android 
float targetHeight = DWUtilities.convertDpToPixel(80, getActivity()); 
float targetWidth = DWUtilities.convertDpToPixel(80, getActivity()); 

// However, the above pixel dimension are still too small to show in my 80dp image view 
// On the Nexus 4, a factor of 4 seems to get us up to the right size 
// No idea why. 
targetHeight *= 4; 
targetWidth *= 4; 

matrix.postScale((float) targetHeight/square.getWidth(), (float) targetWidth/square.getHeight()); 


Bitmap resizedBitmap = Bitmap.createBitmap(square, 0, 0, square.getWidth(), square.getHeight(), matrix, false); 

// By the way, the below code also gives a full size, but blurry image 
// Bitmap resizedBitmap = Bitmap.createScaledBitmap(square, (int) targetWidth, (int) targetHeight, false 

我還沒有進一步的解決方案,但希望這對某人有所幫助。