当前位置: 首页 > news >正文

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).

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

转载于:https://www.cnblogs.com/wjtaigwh/p/7206596.html

相关文章:

  • win7下开启web服务器
  • Graylog2+Elasticsearch+Nxlog
  • 初到51CTO
  • iOS多线程与网络开发之小文件上传
  • sqlserver 语句
  • 动态规划 List
  • A useful UrlBuilder class
  • 图解面向对象中的聚合与耦合概念
  • Linux工具使用(5)——FTP
  • Linux下高并发socket最大连接数所受的各种限制
  • 基础研究与国家目标——国家重点基础研究发展计划[转自科学社]
  • java 设计模式 -- 责任链模式
  • CSS的覆盖问题
  • ATL接口返回类型ATL接口返回字符串BSTR*
  • 深入理解JavaScript系列(15):函数(Functions)
  • 网络传输文件的问题
  • 5分钟即可掌握的前端高效利器:JavaScript 策略模式
  • Consul Config 使用Git做版本控制的实现
  • ECS应用管理最佳实践
  • Java方法详解
  • JS实现简单的MVC模式开发小游戏
  • KMP算法及优化
  • PHP的Ev教程三(Periodic watcher)
  • React+TypeScript入门
  • SQLServer之创建显式事务
  • 从零开始的webpack生活-0x009:FilesLoader装载文件
  • 关键词挖掘技术哪家强(一)基于node.js技术开发一个关键字查询工具
  • 基于Vue2全家桶的移动端AppDEMO实现
  • 前端 CSS : 5# 纯 CSS 实现24小时超市
  • 前端临床手札——文件上传
  • 如何解决微信端直接跳WAP端
  • 网页视频流m3u8/ts视频下载
  • 新手搭建网站的主要流程
  • 走向全栈之MongoDB的使用
  • k8s使用glusterfs实现动态持久化存储
  • Salesforce和SAP Netweaver里数据库表的元数据设计
  • zabbix3.2监控linux磁盘IO
  • ​2020 年大前端技术趋势解读
  • ​如何使用ArcGIS Pro制作渐变河流效果
  • ![CDATA[ ]] 是什么东东
  • #{}和${}的区别?
  • $.ajax()
  • (02)Hive SQL编译成MapReduce任务的过程
  • (1综述)从零开始的嵌入式图像图像处理(PI+QT+OpenCV)实战演练
  • (3)llvm ir转换过程
  • (9)STL算法之逆转旋转
  • (C++17) optional的使用
  • (zt)基于Facebook和Flash平台的应用架构解析
  • (利用IDEA+Maven)定制属于自己的jar包
  • (转)Linux下编译安装log4cxx
  • . NET自动找可写目录
  • .[hudsonL@cock.li].mkp勒索病毒数据怎么处理|数据解密恢复
  • .cn根服务器被攻击之后
  • .NET Compact Framework 3.5 支持 WCF 的子集
  • .NET 中的轻量级线程安全