【问题标题】:Scale Bitmap maintaining aspect ratio and fitting both width and height缩放位图保持纵横比并适应宽度和高度
【发布时间】:2016-05-18 12:57:41
【问题描述】:

我想在保持纵横比的情况下缩放位图,但要适合所需的尺寸。 This answer 缩放位图并保持纵横比,但会留下一些空白区域,除非图像是完美的正方形。我需要同时填充宽度和高度,就像 ImageViewFIT_XY ScaleType 属性一样。

【问题讨论】:

    标签: android bitmap scale scaletype


    【解决方案1】:

    基于Streets of Boston's answer,我制作了这个方法,它可以缩放任何位图并将其返回到所需的宽度和高度,同时适合两个尺寸(没有空格!)。它会自动适应更多水平或更多垂直的图像。

    public Bitmap resizeBitmapFitXY(int width, int height, Bitmap bitmap){
        Bitmap background = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        float originalWidth = bitmap.getWidth(), originalHeight = bitmap.getHeight();
        Canvas canvas = new Canvas(background);
        float scale, xTranslation = 0.0f, yTranslation = 0.0f;
        if (originalWidth > originalHeight) {
            scale = height/originalHeight;
            xTranslation = (width - originalWidth * scale)/2.0f;
        }
        else {
            scale = width / originalWidth;
            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(bitmap, transformation, paint);
        return background;
    }
    

    【讨论】:

    • 用这段代码从左右两侧截取图像。
    • @LovekushVishwakarma 这段代码的重点是使任何位图适合任何尺寸而不会不成比例,这意味着有时它会水平或垂直切割以保持方面无线电
    • 不,但我想显示实际图像,并且通过您的代码,它从左侧和右侧切割得太多,我的要求只是调整大小而不是切割左侧和右侧,我想要实际图像调整后的高度和宽度。
    • 我猜这个代码不适合你然后 Lovekush
    猜你喜欢
    • 2016-04-01
    • 2016-01-17
    • 2015-07-31
    • 2014-07-01
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    相关资源
    最近更新 更多