如何像ImageView一样裁剪Bitmap的中心?

28
1个回答

102

你的问题缺少一些关于你想要完成什么的信息,但我猜测你有一个位图并希望将其缩放到新的大小,并且缩放应该像“centerCrop”适用于ImageView一样进行。

来自文档

等比例缩放图像(保持图像的纵横比),以便图像的两个维度(宽度和高度)都等于或大于视图的相应维度(减去填充)。

据我所知,没有一行代码可实现此功能(如果我错了,请纠正我),但是您可以编写自己的方法来实现它。以下方法计算如何将原始位图缩放到新大小并在生成的位图中居中绘制。

希望能对你有所帮助!

public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
    int sourceWidth = source.getWidth();
    int sourceHeight = source.getHeight();

    // Compute the scaling factors to fit the new height and width, respectively.
    // To cover the final image, the final scaling will be the bigger 
    // of these two.
    float xScale = (float) newWidth / sourceWidth;
    float yScale = (float) newHeight / sourceHeight;
    float scale = Math.max(xScale, yScale);

    // Now get the size of the source bitmap when scaled
    float scaledWidth = scale * sourceWidth;
    float scaledHeight = scale * sourceHeight;

    // Let's find out the upper left coordinates if the scaled bitmap
    // should be centered in the new size give by the parameters
    float left = (newWidth - scaledWidth) / 2;
    float top = (newHeight - scaledHeight) / 2;

    // The target rectangle for the new, scaled version of the source bitmap will now
    // be
    RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);

    // Finally, we create a new bitmap of the specified size and draw our new,
    // scaled bitmap onto it.
    Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
    Canvas canvas = new Canvas(dest);
    canvas.drawBitmap(source, null, targetRect, null);

    return dest;
}

我已经尝试过这个了。但是结果图像的质量非常粗糙。我认为裁剪后的图像比原图小,所以在缩放时图像被拉伸得太多了。你能告诉我如何将裁剪框稍微放大一点吗? - Akanksha Rathore
在裁剪顶部和底部时,如果想要避免切角,需要更改哪个参数?请查看以下代码行:RectF(left, top, left + scaledWidth, top + scaledHeight); - Akanksha Rathore
该代码的功能是缩放图像,就像使用ImageView.ScaleType.CENTER_CROP一样。如果原始图像比新的宽度和/或高度小,则会进行放大处理,这可能导致方块状失真。如果您想避免对小图像进行放大缩放,可以在计算缩放比例后添加一行 'if(scale>1)scale = 1;'。这将仅缩小图像,而较小的图像将居中于新矩形内。这回答了您的问题吗? - Albin
@Albin:如何使用ScaleType.centerInside - Mehul Joisar
8
另一种选择:ThumbnailUtils.extractThumbnail(bitmap,width, height); - android developer
显示剩余15条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接