2013-08-19 74 views
1

好吧,所有这些东西折磨我很长一段时间,我设置了一个227像素高的图像,将其缩放到170像素,即使我希望它是wrap_content,我也可以。java Android - 以编程方式处理图像缩放/裁剪

好的。在这里,我把我的图像是1950像素长(我把它放在这里的一部分,所以你可以了解它应该是什么样子)。

enter image description here

首先,我要缩放回227个像素高,因为这是它是如何设计的,它应该如何

Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.ver_bottom_panel_tiled_long); 
      int width = bitmapOrg.getWidth(); 
     int height = bitmapOrg.getHeight(); 
     int newWidth = 200; //this should be parent's whdth later 
     int newHeight = 227; 

     // calculate the scale 
     float scaleWidth = ((float) newWidth)/width; 
     float scaleHeight = ((float) newHeight)/height; 

     // create a 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); 


     BitmapDrawable dmpDrwbl=new BitmapDrawable(resizedBitmap); 

    verbottompanelprayer.setBackgroundDrawable(dmpDrwbl); 

所以......它不是一个裁剪图像在所有 - 不,它是1950像素压入200像素。 enter image description here

,但我想只是削减除了这个200个像素或什么的宽度,我会设置什么 - 作物,而不是按这一切的长形图像为200个像素面积。

另外,BitmapDrawable(位图位图);和imageView.setBackgroundDrawable(drawable);已弃用 - 我该如何改变这种情况?

回答

4

根据我所看到的,您创建了一个新尺寸的位图(200x227),所以我不确定您的预期。你甚至写了一首歌,你扩展的意见和种植无字...

你可以做的是:

  1. 如果API是至少10(姜饼),你可以使用BitmapRegionDecoder,使用decodeRegion

  2. 如果API太旧,需要大量位图解码,然后将它裁剪成一个新的位图,使用Bitmap.createBitmap

是这样的:

final Rect rect =... 
if (VERSION.SDK_INT >= VERSION_CODES.GINGERBREAD_MR1) 
    { 
    BitmapRegionDecoder decoder=BitmapRegionDecoder.newInstance(imageFilePath, true); 
    croppedBitmap= decoder.decodeRegion(rect, null); 
    decoder.recycle(); 
    } 
else 
    { 
    Bitmap bitmapOriginal=BitmapFactory.decodeFile(imageFilePath, null); 
    croppedBitmap=Bitmap.createBitmap(bitmapOriginal,rect.left,rect.top,rect.width(),rect.height()); 
    } 
+0

能否请您给我的例子,如何用Bitmap.CreateBitmap裁剪呢?它只是还没有收获,只是试图把整个图像放进去。可能是我做错了什么? – user2234594

+0

你检查了我刚给你的链接吗?你需要使用正确的功能。无论如何,我写了一个示例代码,但我不确定它是否编译良好。 –

+0

好吧,这就是问题所在 - 我很想使用BitmapRegionDecoder,但它仅适用于文件。但我想用资源 - 不同的dpi。处理文件会使这变得复杂。有什么办法使用BitmapRegionDecoder的资源? – user2234594