Android -- Glide框架详解(一)

1,使用这个框架快两年了,今天去github上去看了一下,貌似已经从3.X升级到4.X了,想着自己还没有对这个框架在博客上做过总结,所以这里打算出三篇博客来介绍,内容有基本使用、3.X与4.X的不通、封装、到最后的源码解析,所以今天从最简单的基本使用开始,废话不多说,开鲁开鲁。。。

2,基本使用

  添加依赖

compile 'com.github.bumptech.glide:glide:3.7.0'

  ① 简单的展示图片

Glide.with(this)
                .load(url)
                .into(iv);

  

  ② 添加占位符和加载动画

  这里的占位符我只是简单的写了个Drawable,对应的方法是placeholder,而动画是直接使用Glide自带的淡入淡出crossFade效果,

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android">
    <shape android:shape="rectangle">
        <gradient
            android:angle="0"
            android:endColor="@android:color/holo_blue_bright"
            android:startColor="@android:color/holo_blue_bright"
            />
        <!--<stroke android:color="#000000" android:width="1dp" />-->
    </shape>
</inset>

  

 Glide.with(this)
                .load(url)
                .placeholder(R.drawable.loading_background)
                .crossFade(3000)
                .error(R.mipmap.ic_launcher)
                .into(iv);

  效果如下:

  ③ 展示本地图片或者gif图片

  这里的展示本地图片就很简单了,把load里面的地址换成我们对应的本地地址就行,很简单。而Gldie相对于Picasso和ImageLoad有不同的是Glide能展示Gif图片而这两个框架不行,而gif展示很简单,和其它的正常图片展示一样

Glide.with(this)
                .load(url2)
                .error(R.mipmap.ic_launcher)
                .into(iv);    

  如果想将该gif当做bitmap来加载,则只需要加上asBitmap()方法,如果想判断该图片是否为gif图片则可以使用asGif()来判断,如果不是的话会展示.error()里面的图片

Glide.with(this)
                .load(url2)
                .asGif()
                .placeholder(R.drawable.loading_background)
                .crossFade(3000)
//                .asBitmap()
                .error(R.mipmap.ic_launcher)
                .into(iv);

  效果如下:

  ④ 加载圆形图片

  这里要使用bitmapTransform(bitmapTransform)方法,方法里面对象是自定义的TransFormation。

  CropCircleTransformation.java

package jp.wasabeef.glide.transformations;

/**
 * Copyright (C) 2017 Wasabeef
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapResource;

public class CropCircleTransformation implements Transformation<Bitmap> {

  private BitmapPool mBitmapPool;

  public CropCircleTransformation(Context context) {
    this(Glide.get(context).getBitmapPool());
  }

  public CropCircleTransformation(BitmapPool pool) {
    this.mBitmapPool = pool;
  }

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

    int width = (source.getWidth() - size) / 2;
    int height = (source.getHeight() - size) / 2;

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

    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    BitmapShader shader =
        new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
    if (width != 0 || height != 0) {
      // source isn't square, move viewport to center
      Matrix matrix = new Matrix();
      matrix.setTranslate(-width, -height);
      shader.setLocalMatrix(matrix);
    }
    paint.setShader(shader);
    paint.setAntiAlias(true);

    float r = size / 2f;
    canvas.drawCircle(r, r, r, paint);

    return BitmapResource.obtain(bitmap, mBitmapPool);
  }

  @Override public String getId() {
    return "CropCircleTransformation()";
  }
}

  使用

 Glide.with(this)
                .load(url)
                .bitmapTransform(new CropCircleTransformation(this))
                .into(iv);

  效果如下:

  ⑤ 添加虚化效果

  编写类BlurTransformation.java

package jp.wasabeef.glide.transformations;

/**
 * Copyright (C) 2017 Wasabeef
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.renderscript.RSRuntimeException;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapResource;
import jp.wasabeef.glide.transformations.internal.FastBlur;
import jp.wasabeef.glide.transformations.internal.RSBlur;

public class BlurTransformation 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 BlurTransformation(Context context) {
    this(context, Glide.get(context).getBitmapPool(), MAX_RADIUS, DEFAULT_DOWN_SAMPLING);
  }

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

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

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

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

  public BlurTransformation(Context context, BitmapPool pool, int radius, int sampling) {
    mContext = context.getApplicationContext();
    mBitmapPool = pool;
    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 "BlurTransformation(radius=" + mRadius + ", sampling=" + mSampling + ")";
  }
}

  使用

 Glide.with(this)
                .load(url)
                .bitmapTransform(new BlurTransformation(this,10))
                .into(iv);

  效果如下:

  以上是我们的一些常用效果,还有一些其他的thumbnail() 缩略图、override()处理图

3. 缓存机制的介绍

  和常见的三级缓存一样,Glide的缓存机制有三种 Glide的缓存书序也是 内存 -- 磁盘 -- 网络

  首先了解一下内存缓存,和内存挂钩的方法就是我们的skipMemoryCache()

Glide.with(this)
                .load(url2)
                .skipMemoryCache(true)
                .into(iv);

  表示是否跳过磁盘缓存,默认的是false

  磁盘缓存

  Glide的磁盘缓存为四种,默认的是result 至于什么是 (有个方法是override方式 意思说是例如 这张图在网上的宽度和高度是 300px*300px 而实际上在我们的移动端ui给我们的效果图是300*150,这时候我们就可以使用这个方法
,将300*300的网络原图处理成300*150 )
  ①.ALL:缓存原图(SOURCE)和处理图(RESULT)

  ②.NONE:什么都不缓存

  ③.SOURCE:只缓存原图(SOURCE)

  ④.RESULT:只缓存处理图(RESULT) —默认值

Glide.with(this)
.load(url2)
.override(300,150)
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(iv);

  磁盘缓存目录  项目/cache/image_manager_disk_cache

  关于如何清理缓存内容

       //清除内存缓存
       Glide.get(this).clearMemory();
        //清除磁盘缓存 (要在子线程中进行)
        Glide.get(MainActivity.this).clearDiskCache();

  关于清除单个图片的缓存

    关于清除单个图片缓存  由于Glide可能会缓存一张图片的多个分辨率的图片,并且文件名是被哈希过的,所以并不能很好的删除单个资源的缓存
    谷歌官方解释
      Because File names are hashed keys, there is no good way to simply delete all of the cached files on disk that
        correspond to a particular url or file path. The problem would be simpler if you were only ever allowed to load
        or cache the original image, but since Glide also caches thumbnails and provides various transformations, each
        of which will result in a new File in the cache, tracking down and deleting every cached version of an image
        is difficult.

        In practice, the best way to invalidate a cache file is to change your identifier when the content changes
        (url, uri, file path etc).

  今天没状态,好久没写博客了,状态回来不,感觉自己头脑越来越懒了,改天找回状态接着写

posted @ 2017-07-19 16:46  阿呆哥哥  阅读(1934)  评论(0编辑  收藏  举报