Ris*_*wal 0 android android-layout
我是bitmap的新手.我知道如何在android中调整大小或缩放位图.但问题是假设我的图像是100x500或任何高度和宽度.现在我想在100x100之类的正方形中调整它.如何可能
请帮助我.
对于这个简单的情况,最合理的是将源图像转换为中间,然后在新的Canvas上再次绘制Bitmap.这种类型的调整大小在Android中称为中心裁剪.中心裁剪的想法是产生填充整个边界的最大图像,并且不会改变纵横比.
您可以自己实现此功能,以及其他类型的大小调整和缩放.基本上,您使用Matrix发布更改,例如缩放和移动(翻译),然后在Canvas上绘制原始位图,并考虑Matrix.
这是我从另一个答案中采用的一种方法(无法找到正确的信息):
public static Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth)
{
int sourceWidth = source.getWidth();
int sourceHeight = source.getHeight();
float xScale = (float) newWidth / sourceWidth;
float yScale = (float) newHeight / sourceHeight;
float scale = Math.max(xScale, yScale);
//get the resulting size after scaling
float scaledWidth = scale * sourceWidth;
float scaledHeight = scale * sourceHeight;
//figure out where we should translate to
float dx = (newWidth - scaledWidth) / 2;
float dy = (newHeight - scaledHeight) / 2;
Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
Canvas canvas = new Canvas(dest);
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
matrix.postTranslate(dx, dy);
canvas.drawBitmap(source, matrix, null);
return dest;
}
Run Code Online (Sandbox Code Playgroud)