Android图片加载框架最全解析(五),Glide强大的图片变换功能(笔记)

参考原文:Android图片加载框架最全解析(五),Glide强大的图片变换功能

一个问题

百度这张logo图片的尺寸只有540258像素,但是我的手机的分辨率却是10801920像素,而我们将ImageView的宽高设置的都是wrap_content,那么图片的宽度应该只有手机屏幕宽度的一半而已,但是这里却充满了全屏,这是为什么呢?

Glide.with(this)
     .load(url)
     .dontTransform()
     .into(imageView);
Glide.with(this)
     .load(url)
     .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
     .into(imageView);

图片变换的基本用法

String url = "http://cn.bing.com/az/hprichbg/rb/AvalancheCreek_ROW11173354624_1920x1080.jpg";
Glide.with(this)
     .load(url)
     .override(500, 500)
     .centerCrop()
     .into(imageView);

源码分析

首先,CenterCrop是继承自BitmapTransformation的,这个是重中之重,因为整个图片变换功能都是建立在这个继承结构基础上的。对象连同toTransform、outWidth、outHeight参数一起传入到了TransformationUtils.centerCrop()方法当中

public final class TransformationUtils {
    public static Bitmap centerCrop(Bitmap recycled, Bitmap toCrop, int width, int height) {
        if (toCrop == null) {
            return null;
        } else if (toCrop.getWidth() == width && toCrop.getHeight() == height) {
            return toCrop;
        }
        // From ImageView/Bitmap.createScaledBitmap.
        final float scale;
        float dx = 0, dy = 0;
        Matrix m = new Matrix();
        if (toCrop.getWidth() * height > width * toCrop.getHeight()) {
            scale = (float) height / (float) toCrop.getHeight();
            dx = (width - toCrop.getWidth() * scale) * 0.5f;
        } else {
            scale = (float) width / (float) toCrop.getWidth();
            dy = (height - toCrop.getHeight() * scale) * 0.5f;
        }
        m.setScale(scale, scale);
        m.postTranslate((int) (dx + 0.5f), (int) (dy + 0.5f));

        final Bitmap result;
        if (recycled != null) {
            result = recycled;
        } else {
            result = Bitmap.createBitmap(width, height, getSafeConfig(toCrop));
        }

        // We don't add or remove alpha, so keep the alpha setting of the Bitmap we were given.
        TransformationUtils.setAlpha(toCrop, result);

        Canvas canvas = new Canvas(result);
        Paint paint = new Paint(PAINT_FLAGS);
        canvas.drawBitmap(toCrop, m, paint);
        return result;
    }

自定义图片变换

Glide.with(this)
     .load(url)
     .transform(new CircleCrop(this))
     .into(imageView);

更多图片变换功能

网上出现了很多Glide的图片变换开源库,其中做的最出色的应该要数glide-transformations这个库了。它实现了很多通用的图片变换效果,如裁剪变换、颜色变换、模糊变换等等,使得我们可以非常轻松地进行各种各样的图片变换。
glide-transformations的项目主页地址是 https://github.com/wasabeef/glide-transformations
比如同时执行模糊化和黑白化的变换:

lide.with(this)
     .load(url)
     .bitmapTransform(new BlurTransformation(this), new GrayscaleTransformation(this))
     .into(imageView);

猜你喜欢

转载自blog.csdn.net/fendouwangzi/article/details/82696886