2010-07-06 135 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 

我还没有进一步的解决方案,但希望这对某人有所帮助。