【问题标题】:How to crop Bitmap Center like imageview? [duplicate]如何像imageview一样裁剪位图中心? [复制]
【发布时间】:2011-11-13 15:51:44
【问题描述】:

可能重复:
How to crop the parsed image in android?

如何以与 Android ImageView 相同的方式进行裁剪

android:scaleType="centerCrop"

【问题讨论】:

    标签: android imageview


    【解决方案1】:

    你的问题有点缺乏关于你想要完成什么的信息,但我猜你有一个位图并且想要将它缩放到一个新的大小,并且应该像“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;
    }
    

    【讨论】:

    • 嗨,我可以知道如何从这个位图中给它一个白色边框吗?
    • 您想要在缩放位图顶部添加白色边框,还是想要在其周围添加白色边框,例如填充?
    • @ericlee 这是一个新问题。
    • 我试过这个。但是结果图像质量很粗糙。我认为裁剪后的图像很小,然后图像正在缩放,因此图像拉伸得很大。你能告诉我如何让裁剪框变大一点吗?
    • 另一种选择:ThumbnailUtils.extractThumbnail(bitmap,width,height);
    猜你喜欢
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 2011-03-24
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 2020-09-07
    相关资源
    最近更新 更多