缩放位图保持宽高比 [英] Scaled Bitmap maintaining aspect ratio

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

问题描述

我想缩放位图来运行时依赖的宽度和高度,其中宽比保持不变,并在位图填充整个宽度和垂直居中的图像,无论是裁剪多余或填充在0阿尔法像素的差距。

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阿尔法像素和绘制图像位图在上面的它,缩放的确切指定的宽度和保持纵横比,但是,它最终失去/拧上的像素数据

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;

有一个库在那里或一些更好的code可以做到这一点更好?我想图像看起来脆越好,但我知道我的功能不会提供一个伟大的结果。

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.

另外,我知道了的ImageView Gravity.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(), 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);
Paint paint = new Paint();
paint.setFilterBitmap(true);
canvas.drawBitmap(originalImage, transformation, paint);
return background;

我添加了一个油漆过滤缩放位图。

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

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