Glide加载图片获取自定义大小的Bitmap

需求:加载图片,对其进行大小裁剪并添加圆角

Glide中文文档:Glide v4 : 快速高效的Android图片加载库

首先,如果直接使用glide的链式调用会存在效果覆盖的问题。

通过调研发现需要这样使用

Glide.with(context).asBitmap()

        .load(uri)

        .apply(new RequestOptions().transform(Transformation<Bitmap>... transformations))

        .submit()

        .get()

在transform方法中加入自己定义的BitmapTransformation。

一开始我在自定义的BitmapTransfromation中进行了Bitmap操作,主要是对bitmap进行裁剪和缩放,但是在项目运行之后抛出了com.bumptech.glide.load.engine.GlideException: Failed to load resource异常,调研发现是因为裁剪使原图失真最终导致Glide无法加载原图。

方法一:做法改为调用

TransformationUtils.centerCorp(BitmapPool bitmapPool, Bitmap bitmap, int outWidth, int outHeight)

TransformationUtils.roundedCorners(BitmapPool bitmapPool, Bitmap bitmap, int radius)

将图片按照自己想要的尺寸进行裁剪/切圆角。

方法二:submit(int width, int height)

调研发现可以直接submit(int width, int height)方法直接下载目标尺寸的bitmap

这里贴出centerCrop方法源码:

public static Bitmap centerCrop(@NonNull BitmapPool pool, @NonNull Bitmap inBitmap, int width, int height) {
        if (inBitmap.getWidth() == width && inBitmap.getHeight() == height) {
            return inBitmap;
        } else {
            Matrix m = new Matrix();
            float scale;
            float dx;
            float dy;
            //长短遍适配,srcW/dstW 和 srcH/dstH 大的即为长边,用长边去适配短边
            if (inBitmap.getWidth() * height > width * inBitmap.getHeight()) {
                scale = (float)height / (float)inBitmap.getHeight();
                dx = ((float)width - (float)inBitmap.getWidth() * scale) * 0.5F;
                dy = 0.0F;
            } else {
                scale = (float)width / (float)inBitmap.getWidth();
                dx = 0.0F;
                dy = ((float)height - (float)inBitmap.getHeight() * scale) * 0.5F;
            }

            m.setScale(scale, scale);
            m.postTranslate((float)((int)(dx + 0.5F)), (float)((int)(dy + 0.5F)));
            Bitmap result = pool.get(width, height, getNonNullConfig(inBitmap));
            setAlpha(inBitmap, result);
            applyMatrix(inBitmap, result, m);
            return result;
        }
    }

这里简要记录一下Matrix的pre/set/post方法:

pre是指在setXXX方法前进行的操作,如果调用preScale后又调用setScale,则前者会被覆盖,post则是在setXXX的操作执行后,(例如缩放旋转)进行的操作

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值