gpt4 book ai didi

android - 缩放位图保持纵横比并适应宽度和高度

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:27 24 4
gpt4 key购买 nike

我想缩放保持纵横比但适合所需尺寸的位图。 This answer缩放位图并保持纵横比,但保留一些空白区域,除非图像是完美的正方形。我需要同时填充宽度和高度,就像 ImageViewFIT_XY ScaleType 属性一样。

最佳答案

基于 Streets of Boston's answer ,我制作了这种方法,可以缩放任何位图并将其返回到所需的宽度和高度,适合两个尺寸(无空格!)。它会自动适应更多水平或更多垂直图像。

public Bitmap resizeBitmapFitXY(int width, int height, Bitmap bitmap){
Bitmap background = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
float originalWidth = bitmap.getWidth(), originalHeight = bitmap.getHeight();
Canvas canvas = new Canvas(background);
float scale, xTranslation = 0.0f, yTranslation = 0.0f;
if (originalWidth > originalHeight) {
scale = height/originalHeight;
xTranslation = (width - originalWidth * scale)/2.0f;
}
else {
scale = width / originalWidth;
yTranslation = (height - originalHeight * scale)/2.0f;
}
Matrix transformation = new Matrix();
transformation.postTranslate(xTranslation, yTranslation);
transformation.preScale(scale, scale);
Paint paint = new Paint();
paint.setFilterBitmap(true);
canvas.drawBitmap(bitmap, transformation, paint);
return background;
}

关于android - 缩放位图保持纵横比并适应宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35276834/

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