如何停止Glide的升尺寸?

7
我是使用Glide图片加载库,但在调整位图大小时遇到了问题。
当使用以下代码时:
Glide.with(getActivity())
    .load(images.get(i))
    .asBitmap().centerCrop()
    .into(new SimpleTarget<Bitmap>(1200, 1200) {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {

        }
    });

每一个位图都会被调整到指定的尺寸。因此,如果图像为400x300,则会放大至1200 x 1200,这不是我想要的。如何才能使图像小于指定的尺寸时不进行调整大小?
我指定尺寸是因为我希望每个大于指定尺寸的图像在考虑中心裁剪后进行调整大小;然后,如果图像小于指定尺寸,我不希望其被调整大小。

图像的ScaleType centerCrop会导致您的图像从中心扩展,以便每个边缘都与其布局的View的边界一样大或更大。我不是glide用户,但我认为在asBitmap()之后删除centerCrop()可能会有所帮助--编辑:您还将大小设置为1200x1200,因此您需要以某种方式进行更改。 - Cruceo
@Guardanis 我已经尝试过了,它会完全忽略任何已指定的尺寸。 - Jack
为什么在不想拉伸时要指定尺寸?你想达到什么效果? - headsvk
@headsvk 我指定尺寸是因为我希望每张大于指定尺寸的图片都能够按照 centerCrop 进行调整大小;而如果图片小于指定尺寸,我不希望它被调整大小。 - Jack
1个回答

7
我希望所有尺寸大于指定尺寸的图像都可以进行居中裁剪缩放;如果图像尺寸小于指定尺寸,则不需要进行缩放。您可以使用自定义转换来实现此功能。
public class CustomCenterCrop extends CenterCrop {

    public CustomCenterCrop(BitmapPool bitmapPool) {
        super(bitmapPool);
    }

    public CustomCenterCrop(Context context) {
        super(context);
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        if (toTransform.getHeight() > outHeight || toTransform.getWidth() > outWidth) {
            return super.transform(pool, toTransform, outWidth, outHeight);
        } else {
            return toTransform;
        }
    }
}

然后像这样使用它:

Glide.with(getActivity())
    .load(images.get(i))
    .asBitmap()
    .transform(new CustomCenterCrop(getActivity()))
    .into(new SimpleTarget<Bitmap>(1200, 1200) {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {

        }
    });

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