如何像imageview一样裁剪位图中心?

eri*_*lee 26 android imageview

可能重复:
如何在android中裁剪解析后的图像?

一个人如何按照Androids的ImageView方式进行裁剪

android:scaleType="centerCrop"
Run Code Online (Sandbox Code Playgroud)

Alb*_*bin 91

你的问题是关于你想要完成什么的信息有点缺乏,但我猜你有一个Bitmap,并希望将其缩放到一个新的大小,并且缩放应该完成,因为"centerCrop"适用于ImageViews.

来自Docs

均匀缩放图像(保持图像的纵横比),使图像的尺寸(宽度和高度)等于或大于视图的相应尺寸(减去填充).

据我所知,没有一个人可以做到这一点(请纠正我,如果我错了),但你可以编写自己的方法来做到这一点.以下方法计算如何将原始位图缩放到新大小,并在生成的位图中居中绘制它.

希望能帮助到你!

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 另一种选择:ThumbnailUtils.extractThumbnail(位图,宽度,高度); (7认同)