美文网首页相机-相册
Glide 基本封装使用(二)

Glide 基本封装使用(二)

作者: 因为我的心 | 来源:发表于2019-07-20 22:51 被阅读0次

一、前言:

上一篇:Glide 基本使用(一)

https://www.jianshu.com/p/e350b1fa7f69

为什么选择Glide?

  • Glide 轻量级
  • 速度快
  • 可以根据所需加载图片的大小自动适配所需分辨率的图
  • 支持多种格式图片(静态webp,动态gif,jpeg,jpg,png)
  • 支持多种数据源图片(url,drawable,src,file,asserts,raw)
  • Google主导

Glide的封装就是各种样式,一般包括高斯模糊、圆角、圆形以及矩形圆角等,也可以多种样式混合使用。

二、自定义使用:

Glide配置

1. 在build.gradle中添加依赖:

dependencies {
    //glide的依赖
    compile 'com.github.bumptech.glide:glide:3.7.0'
    //gradle工具类(自定义的类不用导入)
    compile 'jp.wasabeef:glide-transformations:2.0.2'
}

2. 权限

如果是联网获取图片或者本地存储需要添加以下权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

3. 样式展示:

样式展示.pic.jpg

4. GlideUtils类:

/**
 * 网络图片的工具类,自定义的图片的样式
 * <p>
 * (1)ImageView设置图片(错误图片)
 * (2)ImageView设置图片---BitMap(不设置默认图)
 * (3)设置RelativeLayout
 * (4)设置LinearLayout
 * (5)设置FrameLayout
 * (6)高斯模糊------ RelativeLayout
 * (7)高斯模糊------ LinearLayout
 * (8)圆角显示图片  ImageView
 *
 *
 * @author lyy
 */
public class GlideUtils {

    /**
     * (1)
     * 显示图片Imageview
     *
     * @param context  上下文
     * @param errorimg 错误的资源图片
     * @param url      图片链接
     * @param imgeview 组件
     */
    public static void showImageView(Context context, int errorimg, String url,
                                     ImageView imgeview) {
        // 加载图片
        Glide.with(context).load(url)
                // 设置错误图片
                .error(errorimg)
                // 设置淡入淡出效果,默认300ms,可以传参
                .crossFade()
                // 设置占位图
                .placeholder(errorimg)
                // 缓存修改过的图片
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .into(imgeview);
        // Glide.with(context).load(url).thumbnail(0.1f).error(errorimg)
        // .into(imgeview);
        // Glide
        // .with(context)
        // .load(UsageExampleListViewAdapter.eatFoodyImages[0])
        // .placeholder(R.mipmap.ic_launcher) //设置占位图
        // .error(R.mipmap.future_studio_launcher) //设置错误图片
        // .crossFade() //设置淡入淡出效果,默认300ms,可以传参
        // //.dontAnimate() //不显示动画效果
        // .into(imageViewFade);

    }

    /**
     * (2)
     * 获取到Bitmap---不设置错误图片,错误图片不显示
     *
     * @param context
     * @param imageView
     * @param url
     */

    public static void showImageViewGone(Context context,
                                         final ImageView imageView, String url) {
        Glide.with(context).load(url).asBitmap()
                // 缓存修改过的图片
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .into(new SimpleTarget<Bitmap>() {

                    @SuppressLint("NewApi")
                    @Override
                    public void onResourceReady(Bitmap loadedImage,
                                                GlideAnimation<? super Bitmap> arg1) {

                        imageView.setVisibility(View.VISIBLE);
                        BitmapDrawable bd = new BitmapDrawable(loadedImage);
                        imageView.setImageDrawable(bd);
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        // TODO Auto-generated method stub
                        super.onLoadFailed(e, errorDrawable);
                        imageView.setVisibility(View.GONE);
                    }

                });

    }

    /**
     * (3)
     * 设置RelativeLayout
     * <p>
     * 获取到Bitmap
     *
     * @param context
     * @param errorimg
     * @param url
     * @param bgLayout
     */

    public static void showImageView(Context context, int errorimg, String url,
                                     final RelativeLayout bgLayout) {
        // 设置错误图片
        Glide.with(context).load(url).asBitmap().error(errorimg)
               // 缓存修改过的图片
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                // 设置占位图
                .placeholder(errorimg)
                .into(new SimpleTarget<Bitmap>() {

                    @SuppressLint("NewApi")
                    @Override
                    public void onResourceReady(Bitmap loadedImage,
                                                GlideAnimation<? super Bitmap> arg1) {
                        BitmapDrawable bd = new BitmapDrawable(loadedImage);

                        bgLayout.setBackground(bd);

                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        // TODO Auto-generated method stub
                        super.onLoadFailed(e, errorDrawable);

                        bgLayout.setBackgroundDrawable(errorDrawable);
                    }

                });

    }

    /**
     * (4)
     * 设置LinearLayout
     * <p>
     * 获取到Bitmap
     *
     * @param context
     * @param errorimg
     * @param url
     * @param bgLayout
     */

    public static void showImageView(Context context, int errorimg, String url,
                                     final LinearLayout bgLayout) {
        // 设置错误图片
        Glide.with(context).load(url).asBitmap().error(errorimg)
                // 缓存修改过的图片
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                // 设置占位图
                .placeholder(errorimg)
                .into(new SimpleTarget<Bitmap>() {

                    @SuppressLint("NewApi")
                    @Override
                    public void onResourceReady(Bitmap loadedImage,
                                                GlideAnimation<? super Bitmap> arg1) {
                        BitmapDrawable bd = new BitmapDrawable(loadedImage);

                        bgLayout.setBackground(bd);

                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        // TODO Auto-generated method stub
                        super.onLoadFailed(e, errorDrawable);

                        bgLayout.setBackgroundDrawable(errorDrawable);
                    }

                });

    }

    /**
     * (5)
     * 设置FrameLayout
     * <p>
     * 获取到Bitmap
     *
     * @param context
     * @param errorimg
     * @param url
     * @param frameBg
     */

    public static void showImageView(Context context, int errorimg, String url,
                                     final FrameLayout frameBg) {
        // 设置错误图片
        Glide.with(context).load(url).asBitmap().error(errorimg)
                // 缓存修改过的图片
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                // 设置占位图
                .placeholder(errorimg)
                .into(new SimpleTarget<Bitmap>() {

                    @SuppressLint("NewApi")
                    @Override
                    public void onResourceReady(Bitmap loadedImage,
                                                GlideAnimation<? super Bitmap> arg1) {
                        BitmapDrawable bd = new BitmapDrawable(loadedImage);

                        frameBg.setBackground(bd);

                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        // TODO Auto-generated method stub
                        super.onLoadFailed(e, errorDrawable);

                        frameBg.setBackgroundDrawable(errorDrawable);
                    }

                });

    }

    /**
     * (6)自定义
     * 获取到Bitmap 高斯模糊         RelativeLayout
     *
     * @param context
     * @param errorimg
     * @param url
     * @param bgLayout
     */

    public static void showImageViewBlur(Context context, int errorimg,
                                         String url, final RelativeLayout bgLayout) {
        Glide.with(context).load(url).asBitmap().error(errorimg)
                // 设置错误图片
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                // 缓存修改过的图片
                .placeholder(errorimg)
                // 高斯模糊处理
                .transform(new GlideBlurTransformation(context))
                // 设置占位图
                .into(new SimpleTarget<Bitmap>() {

                    @SuppressLint("NewApi")
                    @Override
                    public void onResourceReady(Bitmap loadedImage,
                                                GlideAnimation<? super Bitmap> arg1) {
                        BitmapDrawable bd = new BitmapDrawable(loadedImage);

                        bgLayout.setBackground(bd);

                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        // TODO Auto-generated method stub
                        super.onLoadFailed(e, errorDrawable);

                        bgLayout.setBackgroundDrawable(errorDrawable);
                    }

                });

    }

    /**
     * (7)自定义
     * 获取到Bitmap 高斯模糊 LinearLayout
     *
     * @param context
     * @param errorimg
     * @param url
     * @param bgLayout
     */

    public static void showImageViewBlur(Context context, int errorimg,
                                         String url, final LinearLayout bgLayout) {
        Glide.with(context).load(url).asBitmap().error(errorimg)
                // 设置错误图片

                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                // 缓存修改过的图片
                .placeholder(errorimg)
                // 高斯模糊处理
                .transform(new GlideBlurTransformation(context))
                // 设置占位图
                .into(new SimpleTarget<Bitmap>() {

                    @SuppressLint("NewApi")
                    @Override
                    public void onResourceReady(Bitmap loadedImage,
                                                GlideAnimation<? super Bitmap> arg1) {
                        BitmapDrawable bd = new BitmapDrawable(loadedImage);

                        bgLayout.setBackground(bd);

                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        // TODO Auto-generated method stub
                        super.onLoadFailed(e, errorDrawable);

                        bgLayout.setBackgroundDrawable(errorDrawable);
                    }

                });
    }

    /**
     * (8)自定义
     * 显示图片 圆角显示  ImageView
     *
     * @param context  上下文
     * @param errorimg 错误的资源图片
     * @param url      图片链接
     * @param imgeview 组件
     */
    public static void showImageViewToCircle(Application context, int errorimg,
                                             String url, ImageView imgeview) {
        Glide.with(context).load(url)
                // 设置错误图片
                .error(errorimg)
                // 设置淡入淡出效果,默认300ms,可以传参
                .crossFade()
                // 设置占位图
                .placeholder(errorimg)
                //圆角
                .transform(new GlideCircleTransform(context))
                // 缓存修改过的图片
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .into(imgeview);

        // Glide.with(context).load(url).thumbnail(0.1f).error(errorimg)
        // .into(imgeview);
        // Glide
        // .with(context)
        // .load(UsageExampleListViewAdapter.eatFoodyImages[0])
        // .placeholder(R.mipmap.ic_launcher) //设置占位图
        // .error(R.mipmap.future_studio_launcher) //设置错误图片
        // .crossFade() //设置淡入淡出效果,默认300ms,可以传参
        // //.dontAnimate() //不显示动画效果
        // .into(imageViewFade);

    }

    /**
     *
     * 多种样式(模糊+圆角) ImageView
     *原图基础上变换成圆图 +毛玻璃(高斯模糊)
     * @param context  上下文
     * @param errorimg 错误的资源图片
     * @param url      图片链接
     * @param imgeview 组件
     */
    public static void showImageViewToCircleAndBlur(Application context, int errorimg,
                                                    String url, ImageView imgeview) {
        Glide.with(context).load(url)
                // 设置错误图片
                .error(errorimg)
                // 设置高斯模糊,圆角
                .bitmapTransform(new GlideBlurTransformation(context), new GlideCircleTransform(context))
                // 缓存修改过的图片
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .into(imgeview);
    }
}

4. GlideBlurTransformation类,高斯模糊:

/**
 * 高斯模糊
 */
public class GlideBlurTransformation implements Transformation<Bitmap> {

    private static int MAX_RADIUS = 25;
    private static int DEFAULT_DOWN_SAMPLING = 1;

    private Context mContext;
    private BitmapPool mBitmapPool;

    private int mRadius;
    private int mSampling;

    public GlideBlurTransformation(Context context) {
        this(context, Glide.get(context).getBitmapPool(), MAX_RADIUS,
                DEFAULT_DOWN_SAMPLING);
    }

    public GlideBlurTransformation(Context context, BitmapPool pool) {
        this(context, pool, MAX_RADIUS, DEFAULT_DOWN_SAMPLING);
    }

    public GlideBlurTransformation(Context context, BitmapPool pool, int radius) {
        this(context, pool, radius, DEFAULT_DOWN_SAMPLING);
    }

    public GlideBlurTransformation(Context context, int radius) {
        this(context, Glide.get(context).getBitmapPool(), radius,
                DEFAULT_DOWN_SAMPLING);
    }

    public GlideBlurTransformation(Context context, BitmapPool pool, int radius,
                                   int sampling) {
        mContext = context;
        mBitmapPool = pool;
        mRadius = radius;
        mSampling = sampling;
    }

    public GlideBlurTransformation(Context context, int radius, int sampling) {
        mContext = context;
        mBitmapPool = Glide.get(context).getBitmapPool();
        mRadius = radius;
        mSampling = sampling;
    }

    @Override
    public Resource<Bitmap> transform(Resource<Bitmap> resource, int outWidth,
            int outHeight) {
        Bitmap source = resource.get();

        int width = source.getWidth();
        int height = source.getHeight();
        int scaledWidth = width / mSampling;
        int scaledHeight = height / mSampling;

        Bitmap bitmap = mBitmapPool.get(scaledWidth, scaledHeight,
                Bitmap.Config.ARGB_8888);
        if (bitmap == null) {
            bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight,
                    Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(bitmap);
        canvas.scale(1 / (float) mSampling, 1 / (float) mSampling);
        Paint paint = new Paint();
        paint.setFlags(Paint.FILTER_BITMAP_FLAG);
        canvas.drawBitmap(source, 0, 0, paint);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            try {
                bitmap = RSBlur.blur(mContext, bitmap, mRadius);
            } catch (RSRuntimeException e) {
                bitmap = FastBlur.blur(bitmap, mRadius, true);
            }
        } else {
            bitmap = FastBlur.blur(bitmap, mRadius, true);
        }

        return BitmapResource.obtain(bitmap, mBitmapPool);
    }

    @Override
    public String getId() {
        return "GlideBlurTransformation(radius=" + mRadius + ", sampling="
                + mSampling + ")";
    }
}

5. GlideCircleTransform类,圆角:

/**
 * 圆角Glide
 *
 * @author Administrator
 */
public class GlideCircleTransform extends BitmapTransformation {
    public GlideCircleTransform(Context context) {
        super(context);
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform,
                               int outWidth, int outHeight) {
        return circleCrop(pool, toTransform);
    }

    private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
        if (source == null)
            return null;

        int size = Math.min(source.getWidth(), source.getHeight());
        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;

        // TODO this could be acquired from the pool too
        Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);

        Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP,
                BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);
        return result;
    }

    @Override
    public String getId() {
        return getClass().getName();
    }
}

6. FastBlur类:

/**
 * 高斯模糊需要用的类
 */
public class FastBlur {

    public static Bitmap blur(Bitmap sentBitmap, int radius,
            boolean canReuseInBitmap) {

        Bitmap bitmap;
        if (canReuseInBitmap) {
            bitmap = sentBitmap;
        } else {
            bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
        }

        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16)
                        | (dv[gsum] << 8) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }

        bitmap.setPixels(pix, 0, w, 0, 0, w, h);

        return (bitmap);
    }
}

6. RSBlur类:

public class RSBlur {
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static Bitmap blur(Context context, Bitmap blurredBitmap, int radius)
            throws RSRuntimeException {
        try {
            RenderScript rs = RenderScript.create(context);
            Allocation input = Allocation.createFromBitmap(rs, blurredBitmap,
                    Allocation.MipmapControl.MIPMAP_NONE,
                    Allocation.USAGE_SCRIPT);
            Allocation output = Allocation.createTyped(rs, input.getType());
            ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs,
                    Element.U8_4(rs));

            blur.setInput(input);
            blur.setRadius(radius);
            blur.forEach(output);
            output.copyTo(blurredBitmap);
            rs.destroy();
        } catch (RSRuntimeException e) {
            blurredBitmap = FastBlur.blur(blurredBitmap, radius, true);
        }
        return blurredBitmap;
    }
}

8. 调用工具类:

String url1 = "http://img5.imgtn.bdimg.com/it/u=3691544771,740678494&fm=23&gp=0.jpg";

String url2 = "http://a.hiphotos.baidu.com/image/h%3D200/sign=7f12fce71630e924d0a49b317c096e66/d52a2834349b033b23af1d351cce36d3d539bd3e.jpg";

String url3 = "http://www.5068.com/uploads/allimg/160401/1-160401145114-50.jpg";

private void initView() {
//高斯模糊
GlideUtils.showImageViewBlur(this, R.mipmap.ic_launcher, url1, layout);

//圆角
GlideUtils.showImageViewToCircle(getApplication(), R.mipmap.ic_launcher, url2, cirview);
//relaytiveLay
GlideUtils.showImageView(this, R.mipmap.ic_launcher, url1, relativelayout);

//一般图片,支持imageview,layout
GlideUtils.showImageView(this, R.mipmap.ic_launcher, url2, img);

//多种特效高斯模糊+圆角
GlideUtils.showImageViewToCircleAndBlur(getApplication(), R.mipmap.ic_launcher, url2, imgs);
       
 //矩形圆角
GlideUtils.showImageViewToCircle(getApplication(), R.mipmap.ic_launcher, url2, imgs2);
}

三、工具类使用:

1. 展示效果图:

工具类展示效果图.png

2. GlideLibUtils类:

public class GlideLibUtils {
    /**
     * 实现高斯模糊
     * @param context
     * @param errorimg
     * @param url
     * @param imgeview
     */
    public static void showImageBlur(Application context, int errorimg,
                                                    String url, ImageView imgeview) {
        //radius取值1-25,值越大图片越模糊
        Glide.with(context)
                .load(url)
                .error(errorimg)
                .thumbnail(0.1f)
                .bitmapTransform(new BlurTransformation(context, 15))
                .into(imgeview);
    }


    /**
     * LinearLayout 显示背景的高斯模糊
     * @param context
     * @param errorimg
     * @param url
     * @param bgLayout
     */
    public static void showLinearLayoutBlurBg(Context context, int errorimg,
                                         String url, final LinearLayout bgLayout) {
        Glide.with(context).load(url).asBitmap().error(errorimg)
                // 设置错误图片

                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                // 缓存修改过的图片
                .placeholder(errorimg)
                .thumbnail(0.1f)
                // 高斯模糊处理
                .transform(new BlurTransformation(context))
                // 设置占位图
                .into(new SimpleTarget<Bitmap>() {

                    @SuppressLint("NewApi")
                    @Override
                    public void onResourceReady(Bitmap loadedImage,
                                                GlideAnimation<? super Bitmap> arg1) {
                        BitmapDrawable bd = new BitmapDrawable(loadedImage);

                        bgLayout.setBackground(bd);

                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        // TODO Auto-generated method stub
                        super.onLoadFailed(e, errorDrawable);

                        bgLayout.setBackgroundDrawable(errorDrawable);
                    }

                });

    }

    /**
     * RelativeLayout 显示背景
     * @param context
     * @param errorimg
     * @param url
     * @param bgLayout
     */

    public static void showRelativeLayoutBg(Context context, int errorimg, String url,
                                     final RelativeLayout bgLayout) {
        // 设置错误图片
        Glide.with(context).load(url).asBitmap().error(errorimg)
                // 缓存修改过的图片
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                // 设置占位图
                .placeholder(errorimg)
                .thumbnail(0.1f)
                .into(new SimpleTarget<Bitmap>() {

                    @SuppressLint("NewApi")
                    @Override
                    public void onResourceReady(Bitmap loadedImage,
                                                GlideAnimation<? super Bitmap> arg1) {
                        BitmapDrawable bd = new BitmapDrawable(loadedImage);

                        bgLayout.setBackground(bd);

                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        // TODO Auto-generated method stub
                        super.onLoadFailed(e, errorDrawable);

                        bgLayout.setBackgroundDrawable(errorDrawable);
                    }

                });

    }

    /**
     * 显示原图
     * @param context
     * @param errorimg
     * @param url
     * @param imgeview
     */
    public static void showImage(Context context, int errorimg,
                                           String url, ImageView imgeview) {
        Glide.with(context)
                .load(url)
                .thumbnail(0.1f)
                .error(errorimg)
                .into(imgeview);
    }

    /**
     * 原图基础上变换设置圆形图
     * @param context
     * @param errorimg
     * @param url
     * @param imgeview
     */
    public static void showCircle(Application context, int errorimg,
                                                    String url, ImageView imgeview) {
        Glide.with(context)
                .load(url)
                .error(errorimg)
                .thumbnail(0.1f)
                .bitmapTransform(new CropCircleTransformation(context))
                .into(imgeview);
    }

    /**
     *
     * 多种样式(模糊+圆角) ImageView
     *原图基础上变换成圆图 +毛玻璃(高斯模糊)
     * @param context  上下文
     * @param errorimg 错误的资源图片
     * @param url      图片链接
     * @param imgeview 组件
     */
    public static void showCircleAndBlur(Application context, int errorimg,
                                                    String url, ImageView imgeview) {
        Glide.with(context).load(url)
                // 设置错误图片
                .error(errorimg)
                .thumbnail(0.1f)
                // 设置高斯模糊,圆角
                .bitmapTransform(new BlurTransformation(context, 15), new CropCircleTransformation(context))
                // 缓存修改过的图片
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .into(imgeview);
    }

    /**
     * 原图处理成矩形圆角
     *  ImageView
     * @param context  上下文
     * @param errorimg 错误的资源图片
     * @param url      图片链接
     * @param imgeview 组件
     */
    public static void showRoundedCorners(Application context, int errorimg,
                                                     String url, ImageView imgeview) {
        Glide.with(context).load(url)
                // 设置错误图片
                .error(errorimg)
                .thumbnail(0.1f)
                // 设置矩形圆角
                .bitmapTransform(new RoundedCornersTransformation(context, 30, 0,
                        RoundedCornersTransformation.CornerType.ALL))
                // 缓存修改过的图片
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .into(imgeview);
    }
}

3. 工具类使用:

String url1 = "http://img5.imgtn.bdimg.com/it/u=3691544771,740678494&fm=23&gp=0.jpg";

String url2 = "http://a.hiphotos.baidu.com/image/h%3D200/sign=7f12fce71630e924d0a49b317c096e66/d52a2834349b033b23af1d351cce36d3d539bd3e.jpg";

String url3 = "http://www.5068.com/uploads/allimg/160401/1-160401145114-50.jpg";

private void initView() {
//高斯模糊
GlideLibUtils.showLinearLayoutBlurBg(this, R.mipmap.ic_launcher, url1, layout);

//圆角
GlideLibUtils.showCircle(getApplication(), R.mipmap.ic_launcher, url2, cirview);

//relaytiveLayout
GlideLibUtils.showRelativeLayoutBg(this, R.mipmap.ic_launcher, url1, relativelayout);

 //一般图片,支持imageview,layout
 GlideLibUtils.showImage(this, R.mipmap.ic_launcher, url2, img);

//多种特效高斯模糊+圆角
GlideLibUtils.showCircleAndBlur(getApplication(), R.mipmap.ic_launcher, url2, imgs);

//矩形圆角
GlideLibUtils.showCircle(getApplication(), R.mipmap.ic_launcher, url2, imgs2);
 }

四、gitHub 地址:

相关文章

网友评论

    本文标题:Glide 基本封装使用(二)

    本文链接:https://www.haomeiwen.com/subject/ovrplctx.html