缩放位图保持纵横比 [英] Scaled Bitmap maintaining aspect ratio

查看:20
本文介绍了缩放位图保持纵横比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 Bitmap 缩放到依赖于运行时的宽度和高度,其中保持纵横比并且 Bitmap 填充整个宽度并使图像垂直居中,要么裁剪多余的部分,要么用 0 个 alpha 像素填充间隙.

I would like to scale a Bitmap to a runtime dependant width and height, where the aspect ratio is maintained and the Bitmap fills the entire width and centers the image vertically, either cropping the excess or filling in the gap with 0 alpha pixels.

我目前正在重绘位图,方法是创建一个所有 0 alpha 像素的 Bitmap 并在其上绘制图像 Bitmap,缩放到精确的指定宽度并保持纵横比,然而,它最终会丢失/搞砸像素数据.

I'm currently redrawing the bitmap myself by creating a Bitmap of all 0 alpha pixels and drawing the image Bitmap on top of it, scaling to the exact specified width and maintaining the aspect ratio, however, it ends up losing/screwing up the pixel data.

这是我的做法:

Bitmap background = Bitmap.createBitmap((int)width, (int)height, Config.ARGB_8888);
float originalWidth = originalImage.getWidth(), originalHeight = originalImage.getHeight();
Canvas canvas = new Canvas(background);
float scale = width/originalWidth;
float xTranslation = 0.0f, yTranslation = (height - originalHeight * scale)/2.0f;
Matrix transformation = new Matrix();
transformation.postTranslate(xTranslation, yTranslation);
transformation.preScale(scale, scale);
canvas.drawBitmap(originalImage, transformation, null);
return background;

有没有一个库或一些更好的代码可以更好地做到这一点?我希望图像看起来尽可能清晰,但我知道我的函数不会提供很好的结果.

Is there a library out there or some better code that can do this better? I would like the image to look as crisp as possible, but I knew that my function wouldn't provide a great result.

我知道我可以通过使用整数缩放而不是浮点缩放使图像保持良好状态,但我需要将宽度 100% 填充.

I know I could have the image stay fine by using integer scaling, instead of float scaling, but I need the width to be 100% filled.

此外,我知道 ImageViewGravity.CENTER_CROP 功能,但是,它也使用整数缩放,因此当它出现时它会切断图像的宽度不应该.

Also, I know about an ImageView's Gravity.CENTER_CROP capability, however, that also uses integer scaling, so it cuts off the width of the image when it shouldn't.

推荐答案

关于这个:

Bitmap background = Bitmap.createBitmap((int)width, (int)height, Config.ARGB_8888);

float originalWidth = originalImage.getWidth(); 
float originalHeight = originalImage.getHeight();

Canvas canvas = new Canvas(background);

float scale = width / originalWidth;

float xTranslation = 0.0f;
float 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(originalImage, transformation, paint);

return background;

我添加了一个 paint 来过滤缩放的位图.

I added a paint to filter the scaled bitmap.

这篇关于缩放位图保持纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆