gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:30:58 28 4
gpt4 key购买 nike

好吧,所有这些事情折磨了我好几个星期,我将图像设置为 227 像素高并将其缩放为 170 像素,即使我希望它在任何时候都是 wrap_content。

好的。在这里,我使用了 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(Bitmap 位图);和 imageView.setBackgroundDrawable(drawable);已弃用 - 我该如何更改?

最佳答案

根据我的观察,您创建了一个新大小 (200x227) 的位图,所以我不确定您的期望是什么。你甚至在评论中写了你缩放的内容,但没有关于裁剪的字样......

你可以做的是:

  1. 如果 API 至少为 10 (gingerbread) ,您可以使用 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());
}

关于java Android - 以编程方式处理图像缩放/裁剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18312414/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com