Android - Glide通过"override"和"fitCenter"调整图片大小会使Bitmap变形

6
我使用Glide从相册加载图片到GLSurfaceView中。然而,当我尝试使用override(width, height)来调整图像大小时,它并没有起作用。因此,我添加了fitCenter(),这似乎是获得所需大小的关键。
我的问题是,当Bitmap被调整大小时,结果相当奇怪!一切都很好,除了宽度值较小的图像。附加的图片说明了使用和不使用fitCenter()之间的差异。
这是我用于通过Glide加载的代码。
Glide.with(this)
    .load(imageUri)
    .asBitmap()
    .override(newWidth, newHeight)
    .fitCenter()
    .atMost()
    .into(new SimpleTarget<Bitmap>(newWidth, newHeight) {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
            Log.e(TAG, "Loaded Bitmap Size :" + resource.getWidth() + "x" + resource.getHeight());
            /*
            .
            . Initialize GLSurfaceView with Bitmap resource
            .
            */
        }
    }) ;

我想了一秒钟,可能是GLSurfaceView的问题,我猜可能与非常小的宽度有关。但是看起来它在图像被调整大小之前渲染得很完美。

我的代码有什么问题吗? 我真的很感谢任何建议。

enter image description here

1个回答

1

看起来问题出现在使用fitCenter()GLSurfaceView以及一个宽度或高度为奇数的Bitmap时。我通过在Glide调用中添加以下自定义转换来解决了这个问题。

@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int maxWidth, int maxHeight) {
    if (maxHeight > 0 && maxWidth > 0) {
        int width = toTransform.getWidth();
        int height = toTransform.getHeight();

        float ratioBitmap = (float) width / (float) height;
        float ratioMax = (float) maxWidth / (float) maxHeight;

        int finalWidth = maxWidth;
        int finalHeight = maxHeight;
        if (ratioMax > ratioBitmap) {
            finalWidth = (int) ((float) maxHeight * ratioBitmap);
        } else {
            finalHeight = (int) ((float)maxWidth / ratioBitmap);
        }

        return Bitmap.createScaledBitmap(toTransform, previousEvenNumber(finalWidth), previousEvenNumber(finalHeight), true);
    }
    else {
        return toTransform;
    }
}

private int previousEvenNumber(int x){
    if ( (x & 1) == 0 )
        return x;
    else
        return x - 1;
}

并将编辑Glide的调用更改为以下内容:

Glide.with(this)
    .load(imageUri)
    .asBitmap()
    .override(newWidth, newHeight)
    .transform(new CustomFitCenter(this))
    .into(new SimpleTarget<Bitmap>() {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
            Log.e(TAG, "Loaded Bitmap Size :" + resource.getWidth() + "x" + resource.getHeight());
            /*
            .
            . Initialize GLSurfaceView with Bitmap resource
            .
            */
        }
    }) ;

我不确定这是否是最好的方法,但它起作用了。


这个答案是由OP Zac Jokface 在CC BY-SA 3.0下发布的,作为对问题Android - Glide resizing image via "override" and "fitCenter" deforms Bitmap编辑


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