java Android – 以编程方式处理图像缩放/裁剪

好吧,所有这一切都折磨了我很长一段时间,我设置了一个高达227像素的图像,它的高度为170像素,即使我希望它在任何时候都是wrap_content。

好。 在这里,我拍摄了1950像素长的My Image(我在这里放了一部分,这样你就可以理解它应该是什么样子了)。

在此处输入图像描述

首先,我想将其缩放到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像素。 在此处输入图像描述

但是我想要除了这个200像素或我设置的任何宽度之外切割任何东西 – 裁剪它而不是将所有这些长图像按到200像素区域。

另外,BitmapDrawable(位图位图); 和imageView.setBackgroundDrawable(drawable); 已弃用 – 我该如何更改?

根据我所看到的,你创建一个新的大小(200×227)的位图,所以我不确定你的期望。 你甚至在评论中写了你的规模,没有关于裁剪的消息……

你能做的是:

  1. 如果API至少为10(姜饼),则可以使用decodeRegion来使用BitmapRegionDecoder :

  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()); }