Glide4.7.1的使用

版本:Glide4.7.1
1.配置
1.1.新建一个MyAppGlideModule继承AppGlideModule,建议使用官方使用的方法,方便后续需求而进行拓展配置

@GlideModule
public class MyAppGlideModule extends AppGlideModule {


    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {

        //下面3中设置都可自定义大小,以及完全自定义实现
        //内存缓冲
        MemorySizeCalculator calculator = new MemorySizeCalculator.Builder(context)
                .setMemoryCacheScreens(2)
                .setBitmapPoolScreens(3)
                .build();
        builder.setMemoryCache(new LruResourceCache(calculator.getMemoryCacheSize()));

        //Bitmap 池
        builder.setBitmapPool(new LruBitmapPool(calculator.getBitmapPoolSize()));

        //磁盘缓存
        int diskCacheSizeBytes = 1024 * 1024 * 100;  //100 MB
        builder.setDiskCache(new InternalCacheDiskCacheFactory(context, diskCacheSizeBytes));



    }
}

1.2.新建一个封装类GlideUtil,方便以后得维护。目前没有进行很好的封装,方便自己的需求添加,可以根据自己的需要进行修改

/**
 * 创建日期:2018/11/23 on 10:38
 * 描述: glide工具类
 */
public class GlideUtil {


    private static GlideUtil instance;
    RequestOptions options;
    Context mContext;

    private GlideUtil(Context context){
        options = new RequestOptions();
        options.skipMemoryCache(false);
        options.diskCacheStrategy(DiskCacheStrategy.ALL);
        options.priority(Priority.HIGH);
        options.error(R.mipmap.home_img_loading_pic1);
        //设置占位符,默认
        options.placeholder(R.mipmap.home_img_loading_pic1);
        //设置错误符,默认
        options.error(R.mipmap.home_img_loading_pic1);
        mContext=context;
    }

    public static GlideUtil getInstance(Context context){
        if (instance==null){
            synchronized (GlideUtil.class){
                if (instance==null){
                    instance=new GlideUtil(context);
                }
            }
        }
        return instance;
    }

    //设置占位符
    public void setPlaceholder(int id){
        options.placeholder(id);
    }
    public void setPlaceholder(Drawable drawable){
        options.placeholder(drawable);
    }

    //设置错误符
    public void setError(int id){
        options.error(id);
    }

    public void setError(Drawable drawable){
        options.error(drawable);
    }

    public void showImage(String url, ImageView imageView){

        GlideApp.with(mContext)
                .load(url)
                .apply(options)
                .into(imageView);

    }

    //以图片宽度为基准
    public void showImageWidthRatio(String url, final ImageView imageView, final int width){
        GlideApp.with(mContext)
                .asBitmap()
                .apply(options)
                .load(url)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int imageWidth=resource.getWidth();
                        int imageHeight=resource.getHeight();
                        int height = width * imageHeight / imageWidth;
                        ViewGroup.LayoutParams params=imageView.getLayoutParams();
                        params.height=height;
                        params.width=width;
                        imageView.setImageBitmap(resource);
                    }
                });
    }

    //以图片高度为基准
    public void showImageHeightRatio(String url, final ImageView imageView, final int height){
        GlideApp.with(mContext)
                .asBitmap()
                .apply(options)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int imageWidth=resource.getWidth();
                        int imageHeight=resource.getHeight();
                        int width = height * imageHeight / imageWidth;
                        ViewGroup.LayoutParams params=imageView.getLayoutParams();
                        params.height=height;
                        params.width=width;
                        imageView.setImageBitmap(resource);
                    }
                });
    }

    //设置图片固定的大小尺寸
    public void showImageWH(String url, final ImageView imageView, int height,int width){

        options.override(width,height);
        GlideApp.with(mContext)
                .load(url)
                .apply(options)
                .into(imageView);
    }

    //设置图片圆角,以及弧度
    public void showImageRound(String url, final ImageView imageView,int radius){

        options.transform(new CornersTranform(radius));
//        options.transform(new GlideCircleTransform());
        GlideApp.with(mContext)
                .load(url)
                .apply(options)
                .into(imageView);

    }

    public void showImageRound(String url, final ImageView imageView,int radius, int height,int width){
        //不一定有效,当原始图片为长方形时设置无效
        options.override(width,height);
        options.transform(new CornersTranform(radius));
//        options.centerCrop(); //不能与圆角共存
        GlideApp.with(mContext)
                .load(url)
                .apply(options)
                .into(imageView);

    }


    public void showImageRound(String url, final ImageView imageView){
        //自带圆角方法,显示圆形
        options.circleCrop();
        GlideApp.with(mContext)
                .load(url)
                .apply(options)
                .into(imageView);
    }
}

1.3使用方式

 GlideUtil.getInstance(context).showImageRound(aNew.getImages_urls().get(0),vh.img_news_pic1);

2.特殊需求,以及注意事项
2.1挡我们需要给图片使用圆角的时候我们需要进行一些处理。
有两种方式:
a.可以根据Glide提供扩展接口自己实现方法(4.0之前和之后的版本的实现方式有点不一样)


/**
 * glide处理圆角图片\
 */

public class CornersTranform extends BitmapTransformation {
    private float radius;

    public CornersTranform() {
        super();
        radius = 10;
    }

    public CornersTranform(float radius) {
        super();
        this.radius = radius;
    }

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

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

        Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);

        if (result != null && !result.isRecycled()){
            result.recycle();
            result = null;
        }

        if (result == null) {
            result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        }
        Canvas canvas = new Canvas(result);
        Paint paint  = new Paint();
        paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
        canvas.drawRoundRect(rectF, radius, radius, paint);
        return result;
    }

    @Override
    public void updateDiskCacheKey(MessageDigest messageDigest) {

    }
}

实现方法

    public void showImageRound(String url, final ImageView imageView,int radius, int height,int width){
        //不一定有效,当原始图片为长方形时设置无效
        options.override(width,height);
        options.transform(new CornersTranform(radius));
//        options.centerCrop(); //不能与圆角共存
        GlideApp.with(mContext)
                .load(url)
                .apply(options)
                .into(imageView);

    }

上面的方式可以自定义圆角弧度的,注意不能options.centerCrop();一起使用,因为一起使用会让圆角失效(原因网上已经有解释以及实现共存方式)
glide官方还提供了 options.circleCrop();方法这是实现圆形的图片

  //自带圆角方法,显示圆形
        options.circleCrop();
        GlideApp.with(mContext)
                .load(url)
                .apply(options)
                .into(imageView);

b.上面的方式个人感觉不是太友好,我采取的是自定义一个实现圆角的控件
RoundImageView实现圆角弧度,实现和使用简单,但不能随意修改


/**
 * 创建日期:2018/10/19 on 15:38
 * 描述: 自定义圆角图片
 */
public class RoundImageView extends AppCompatImageView {


    //圆角大小,默认为10
    private int mBorderRadius = 10;

    private Paint mPaint;

    // 3x3 矩阵,主要用于缩小放大
    private Matrix mMatrix;

    //渲染图像,使用图像为绘制图形着色
    private BitmapShader mBitmapShader;

    public RoundImageView(Context context) {
        this(context, null);
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mMatrix = new Matrix();
        mPaint = new Paint();
        mPaint.setAntiAlias(true);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (getDrawable() == null){
            return;
        }
        Bitmap bitmap = drawableToBitamp(getDrawable());
        mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        float scale = 1.0f;
        if (!(bitmap.getWidth() == getWidth() && bitmap.getHeight() == getHeight()))
        {
            // 如果图片的宽或者高与view的宽高不匹配,计算出需要缩放的比例;缩放后的图片的宽高,一定要大于我们view的宽高;所以我们这里取大值;
            scale = Math.max(getWidth() * 1.0f / bitmap.getWidth(),
                    getHeight() * 1.0f / bitmap.getHeight());
        }
        // shader的变换矩阵,我们这里主要用于放大或者缩小
        mMatrix.setScale(scale, scale);
        // 设置变换矩阵
        mBitmapShader.setLocalMatrix(mMatrix);
        // 设置shader
        mPaint.setShader(mBitmapShader);
        canvas.drawRoundRect(new RectF(0,0,getWidth(),getHeight()), mBorderRadius, mBorderRadius,
                mPaint);
    }


    private Bitmap drawableToBitamp(Drawable drawable)
    {
        if (drawable instanceof BitmapDrawable)
        {
            BitmapDrawable bd = (BitmapDrawable) drawable;
            return bd.getBitmap();
        }
        // 当设置不为图片,为颜色时,获取的drawable宽高会有问题,所有当为颜色时候获取控件的宽高
        int w = drawable.getIntrinsicWidth() <= 0 ? getWidth() : drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight() <= 0 ? getHeight() : drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;
    }
}

//使用:在对应的布局文件中使用
 <com.bestapp.myglidedemo.image.RoundImageView
                android:id="@+id/img_news_pic1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/news_type_bottom"
                android:scaleType="centerCrop"
                android:src="@mipmap/home_img_loading_pic1" />

CustomRoundAngleImageView实现比较复杂,但是可以单独随意定义4个角的弧度

/**
 * 创建日期:2018/10/22 on 11:24
 */
public class CustomRoundAngleImageView extends AppCompatImageView {
    float width, height;

    public CustomRoundAngleImageView(Context context) {
        this(context, null);
        init(context, null);
    }

    public CustomRoundAngleImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        init(context, attrs);
    }

    public CustomRoundAngleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }
    private int defaultRadius = 0;
    private int radius;
    private int leftTopRadius;
    private int rightTopRadius;
    private int rightBottomRadius;
    private int leftBottomRadius;

    private void init(Context context, AttributeSet attrs) {
        if (Build.VERSION.SDK_INT < 18) {
            setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }


        // 读取配置
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.Custom_Round_Image_View);
        radius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_radius, defaultRadius);
        leftTopRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_left_top_radius, defaultRadius);
        rightTopRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_right_top_radius, defaultRadius);
        rightBottomRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_right_bottom_radius, defaultRadius);
        leftBottomRadius = array.getDimensionPixelOffset(R.styleable.Custom_Round_Image_View_left_bottom_radius, defaultRadius);


        //如果四个角的值没有设置,那么就使用通用的radius的值。
        if (defaultRadius == leftTopRadius) {
            leftTopRadius = radius;
        }
        if (defaultRadius == rightTopRadius) {
            rightTopRadius = radius;
        }
        if (defaultRadius == rightBottomRadius) {
            rightBottomRadius = radius;
        }
        if (defaultRadius == leftBottomRadius) {
            leftBottomRadius = radius;
        }
        array.recycle();


    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        width = getWidth();
        height = getHeight();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //这里做下判断,只有图片的宽高大于设置的圆角距离的时候才进行裁剪
        int maxLeft = Math.max(leftTopRadius, leftBottomRadius);
        int maxRight = Math.max(rightTopRadius, rightBottomRadius);
        int minWidth = maxLeft + maxRight;
        int maxTop = Math.max(leftTopRadius, rightTopRadius);
        int maxBottom = Math.max(leftBottomRadius, rightBottomRadius);
        int minHeight = maxTop + maxBottom;
        if (width >= minWidth && height > minHeight) {
            Path path = new Path();
            //四个角:右上,右下,左下,左上
            path.moveTo(leftTopRadius, 0);
            path.lineTo(width - rightTopRadius, 0);
            path.quadTo(width, 0, width, rightTopRadius);

            path.lineTo(width, height - rightBottomRadius);
            path.quadTo(width, height, width - rightBottomRadius, height);

            path.lineTo(leftBottomRadius, height);
            path.quadTo(0, height, 0, height - leftBottomRadius);

            path.lineTo(0, leftTopRadius);
            path.quadTo(0, 0, leftTopRadius, 0);

            canvas.clipPath(path);
        }
        super.onDraw(canvas);
    }

}

新建一个资源文件attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="Custom_Round_Image_View">
        <attr name="radius" format="dimension"/>
        <attr name="left_top_radius" format="dimension"/>
        <attr name="right_top_radius" format="dimension"/>
        <attr name="right_bottom_radius" format="dimension"/>
        <attr name="left_bottom_radius" format="dimension"/>
    </declare-styleable>

</resources>

使用


            <com.bestapp.myglidedemo.image.CustomRoundAngleImageView
                android:id="@+id/img_type3_pic1"
                android:layout_width="200px"
                android:layout_height="200px"
                android:scaleType="centerCrop"
                app:left_top_radius="10px"
                app:left_bottom_radius="10px"
                android:src="@mipmap/home_img_loading_pic1" />

注意:com.bestapp.myglidedemo.image.是自己文件所在的路径,根据自己的情况修改

2.2设置图片宽高
2.2.1 根据宽度为基准设置图片宽高

//以图片宽度为基准
    public void showImageWidthRatio(String url, final ImageView imageView, final int width){
        GlideApp.with(mContext)
                .asBitmap()
                .apply(options)
                .load(url)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int imageWidth=resource.getWidth();
                        int imageHeight=resource.getHeight();
                        int height = width * imageHeight / imageWidth;
                        ViewGroup.LayoutParams params=imageView.getLayoutParams();
                        params.height=height;
                        params.width=width;
                        imageView.setImageBitmap(resource);
                    }
                });
    }

2.2.2根据高度为基准设置图片宽高

 //以图片高度为基准
    public void showImageHeightRatio(String url, final ImageView imageView, final int height){
        GlideApp.with(mContext)
                .asBitmap()
                .apply(options)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int imageWidth=resource.getWidth();
                        int imageHeight=resource.getHeight();
                        int width = height * imageHeight / imageWidth;
                        ViewGroup.LayoutParams params=imageView.getLayoutParams();
                        params.height=height;
                        params.width=width;
                        imageView.setImageBitmap(resource);
                    }
                });
    }

2.2.3单独设置宽高使用options.override(width,height);方法

总结:基本可以概括了一般的使用,当然还有更高级的使用还没有涉及到。本文是根据本人自己的项目情况遇到的问题来写的,当然同时借鉴了网上的东西,有什么不对的希望指出。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,585评论 4 365
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,923评论 1 301
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,314评论 0 248
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,346评论 0 214
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,718评论 3 291
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,828评论 1 223
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,020评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,758评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,486评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,722评论 2 251
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,196评论 1 262
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,546评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,211评论 3 240
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,132评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,916评论 0 200
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,904评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,758评论 2 274

推荐阅读更多精彩内容