许久没看到有意思的文章了,今天分享下在项目里面 glide 的用法吧,整理分享出来。

能够简单一句话加载图片,dsl 方法添加各种配置,提高开发效率

其实也不是什么高深东西,喜欢可以拿去用,仓库在文末:

简单使用:

先自己依赖 glide:

implementation "com.github.bumptech.glide:glide:$glide_version"

然后可以使用了:

  imageView.loadImage(url)

如果加载的 resource 属于 Animatable,会自动调用 start()

配置加载参数:

  ImageView.loadImage(url){
    placeholder()      //占位,提供了 resId 和 drawable 两个方法
    error()            //错误占位,提供了 resId 和 drawable 两个方法
    decodeFormat()     //对应 Glide 的 format 配置
    centerCrop()       //显示模式,对应 centerCrop
    centerInside()     //显示模式,对应 centerInside
    fitCenter()        //显示模式,对应 fitCenter
    skipLocalCache()   //跳过缓存,下面几个都是
    skipNetCache()
    skipMemoryCache()
    skipOverride()     // 设置这个,就不会执行 override,即使设置了宽高
    circleCrop()       //圆形
    roundAngle()       //圆角
    maskColor()        //设置遮照颜色
    dontAnimate()      //不要动画
    blur()             //高斯模糊
    targetSize()       //设置宽高
    grayImage()        //彩色置灰
  }

如上,可以设置很多种基础配置。

加载回调

  1. 回调 drawable
imageView.loadImage(url){
    requestListener {
        onDrawableSuccess { drawable ->
           //...
        }
        onLoadFailed { 
            //...
        }
    }
}
也可以这样:
context.loadImage(url){
    requestListener {
        onDrawableSuccess { drawable ->
            imageView.setImageDrawable(drawable)
        }
    }
}
  1. 回调 bitmap,同理,不过需要调用 asBitmap
imageView.loadImage(url){
    asBitmap()
    requestListener {
        onBitmapSuccess { drawable ->
           //...
        }
    }
}

加载 gif

  imageView.loadImage(url){ asGif() }

asGif() 有个参数 getGifDrawable,默认 false,true 的话会在 onDrawableSuccess 里面得到 GifDrawable

加载 webp 动画

  imageView.loadImage(url){ webpGif() }

webp动画需要自己依赖解码库:

  implementation "com.zlc.glide:webpdecoder:2.0.4.12.0"

加载 svga

加载svga需要自己依赖svga库:

    implementation("com.github.yyued:SVGAPlayer-Android:2.6.1")

然后加载 svga 可选择用 Glide 去加载或者用 svga 自己的加载器加载,推荐用 glide 加载,需要自己依赖:

 // 手Y SVGA管理
   implementation('com.github.YvesCheung:SVGAGlidePlugin:4.13.3') {
        exclude group: 'com.github.yyued', module: 'SVGAPlayer-Android'
   }

然后使用:

  imageView.loadImage(url){ asSvga() }

默认使用的是 glide 加载,不想的话 asSvga(false) 即可。

回调的话也是一样:

context.loadImage(url) {
    asSvga() 
    requestListener {
        onSvgaSuccess { entity, width, height, drawable ->
           //...
        }
    }
}

给 svga 添加 key:

context.loadImage(svgaTitle) {
    asSvga()
    addSvgaText {
        key = ""     //key
        text = ""    //文案 
        colorString = "#FFFFFF"  //颜色
        textSize = 20f.sp2px  //字体大小
        typeface = FontCache.getTypeface("XXX.ttf", context) //字体
    }
    addSvgaText {} //可添加多个
    //...
    addSvgaImage{
        key = ""     //key
        url=""     //图片url
    }
    addSvgaImage {} //可添加多个
    //...
    requestListener {
        onSvgaSuccess { entity, width, height, drawable ->
            svgaView?.setImageDrawable(drawable)
            svgaView?.startAnimation()
        }
    }
}

仓库地址:github.com/EspoirX/Gli…