本文主要是介绍(源码分析)Glide(图片异步加载缓存库)的方法介绍(附封装的工具类),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本系列带将一步步带领大家揭开Glide的神秘面纱
文章来源:编程之美_CodingForAndroid_CSDN博客。
Glide 在开源中国上的介绍
- Glide 的详细介绍:请点这里
- Glide 的下载地址:请点这里
Glide :
An image loading and caching library for Android focused on smooth scrolling
安卓上专注于平滑滑动的图片加载和缓存库。
Glide有以下特点:
1.生命周期:图片的加载、GIF图片的播放,可和页面的生命周期一致。可接受Activity、Fragment、FragmentActivity、ApplicationContext。
实现原理:
Glide对每个页面维护了一个单独的RequestManager。
对于每一个Activity或Fragment,在其中添加一个RequestManagerFragment作为子Fragment,其生命周期和父组件Activity或Fragment的生命周期一致,在RequestManagerFragment中onStart、onStop、onDestroy中调用相应方法。
对于ApplicationContext,只调用了onStart方法。
优点: 可自动根据页面生命周期,开始/暂停加载图片、展示动态图片。
缺点: 会消耗更多资源。使用时如果不了解相关特性,容易出错。
2.相比Fresco,没有使用JNI
优点: 不容易出现JNI相关的错误,配置更容易
缺点: 相比Fresco,性能可能稍差,OOM的概率可能多一点
3.Bitmap解码格式:默认优先使用RGB_565,比ARGB_8888内存占用减少一半,性能好。可全局配置优先使用RGB_565或ARGB_8888,也可对某个请求单独配置。Fresco也可以支持两种编码,而Picasso只支持ARGB_8888。
4.磁盘缓存策略:默认使用了内存LRU缓存和磁盘LRU缓存。磁盘缓存支持配置缓存全尺寸、转换过的尺寸、两者都保存。可全局配置,或对某个请求单独配置。
Picasso内部只实现了内存LRU缓存,磁盘缓存直接使用了OKHTTP的缓存,只能缓存下载的原始图片,每次从磁盘加载都要转换。
5.内存缓存策略:使用了两级内存缓存,MemoryCache和ActiveResource,前者默认为一个LruResourceCache,后者是一个Map弱引用,引用了从MemoryCache中读取过的资源和从网络、硬盘下载和转换出的资源。
加载图片时先使用MemoryCache,如果没有找到则尝试从ActiveResource中获取资源。如果还是没有再从磁盘、网络获取资源。
6.BitmapPool:进行Bitmap相关的操作时,对Bitmap进行缓存和复用。默认实现的是LruBitmapPool(仅支持Android 3.0及以上版本)。
7.网络图片下载:网络图片默认使用HttpURLConnection加载(HttpUrlFetcher),可以通过注册模块的形式,设置成Volley或OkHttp等。
8.相比Fresco,不需要特定的View,直接使用ImageView即可,通用性好
9.可以暂停、继续、清除某个页面的RequestManager中所有请求。和Picasso相似(Picasso通过Tag来对Request分组进行操作)。
10.尺寸适配:默认自动根据图片尺寸加载对应的图片。Picasso则需要显示调用fit()方法。
11.图片转换:配合glide-transformations,可对图片实现裁剪,着色,模糊,滤镜等效果。
12.预加载:提供了一个ListPreloader类,可用于AbsListView的预加载
原理:ListPreloader中实现了OnScrollListener,滚动时自动计算并预加载,所加载的Target为PreloadTarget。
13.加载动态图:支持GIF和本地视频加载,并根据页面生命周期播放/暂停
14.默认网络请求使用的是httpurlconnection,同时支持自定义使用volley 或者 ok。
15.自定义多个请求的优先级,重要的图片,可以设置高的优先级,优先加载。
16.可以给url 设置一个签名,当url 指向不变,图片内容变化时,根据签名不同,去自动更换以缓存的图片,这一点是imagoader无法做到的。
17.更有一个非常优秀的特点,可以在非ImageView 类型上面加载图片。
更多优点,不一一总结,留待大家亲身使用感受。
获取Glide
首先获取Glide的jar包,可以去github下载,添加依赖,也可以使用gradle 下载。
You can download a jar from GitHub's releases page.
Or use Gradle:
repositories {mavenCentral() // jcenter() works as well because it pulls from Maven Central
}dependencies {compile 'com.github.bumptech.glide:glide:3.7.0'compile 'com.android.support:support-v4:19.1.0'
}
How do I use Glide?
// For a simple view:
@Override public void onCreate(Bundle savedInstanceState) {...ImageView imageView = (ImageView) findViewById(R.id.my_image_view);Glide.with(this).load("http://goo.gl/gEgYUd").into(imageView);
}// For a simple image list:
@Override public View getView(int position, View recycled, ViewGroup container) {final ImageView myImageView;if (recycled == null) {myImageView = (ImageView) inflater.inflate(R.layout.my_image_view, container, false);} else {myImageView = (ImageView) recycled;}String url = myUrls.get(position);Glide.with(myFragment).load(url).centerCrop().placeholder(R.drawable.loading_spinner).crossFade().into(myImageView);return myImageView;
}
可以看出Glide 的使用时相当简便的,添加依赖后,仅仅通过Glide.with().load().into();就可以展示远程图片。
以上便是Github上关于Glide的基本介绍,接下来我们看具体的使用。
Glide 使用起来非常简单,Glide 在Activity 、Fragment 中都可以使用,并且是通过绑定对应的对象去使用。
Glide.with(this).load(url).into(imageView);
这就是最基本的使用方式 。
with() :使Glide 的生命周期与当前对象绑定,可以是Activity Fragment Context等等。
load():可以加载一个本地图片,或者网络图片地址,也可以是Android工程的 内部Resource 图片资源。
into():将展示在ImageView 对象。
介绍一些常用的配置:
Glide基本方法:Glide.with(this).load(R.mipmap.bigger).into(imageView);
加载网络图片时显示的占位图:.placeholder(holderId).into(imageView);
加载失败时展示的失败图:.error(errorId).into(imageView);
淡入淡出的渐变展示过渡动画:.crossFade().into(imageView);淡入淡出的渐变展示过渡动画 crossFade(int millSeconds) 默认Glide是自动执行该方法的,淡入时间是300ms (可以自己传int 参数去调整时间),如果要禁止该效果,可以调用dontAnimate() 方法
按比例缩小或者放大到ImageView宽度,居中显示:.fitCenter().into(imageView);
按比例放大图片居中显示,图片的长/宽 可能大于ImageView的长/宽:.centerCrop().into(imageView);。
priority( Priority.HIGH ):设置请求的优先级 由低到高分别为: Priority.LOW、 Priority.NORMAL、 Priority.HIGH 、 Priority.IMMEDIATE。
skipMemoryCache( true ) :是否设置不允许内存缓存,如果是比较频繁的变化,那么可以不在内存中保存,默认是false,即允许内存缓存。
diskCacheStrategy():设置磁盘缓存策略,因为默认情况下 Glide 不仅仅会缓存远程图片,并且会缓存适应当前View size的图片。
参数为枚举类型 有四种分辨是:
DiskCacheStrategy.NONE 什么都不缓存。
DiskCacheStrategy.SOURCE 仅仅只缓存原来的全分辨率的图像。
DiskCacheStrategy.RESULT 仅仅缓存最终的图像,即,降低分辨率后的(或者是转换后的)。
DiskCacheStrategy.ALL 缓存所有版本的图像(默认行为)。
override(int w,int h): 重新调整图片的大小。Glide 加载图片默认是适应ImageView的大小,调用该方法,可能导致图片显示小于ImageView的size。
缩略图:普通方式 .thumbnail(0.1f) 将原图缩小到10%。使用该方法需要保证ImageView的ScaleType。
高级方式通过请求一个额外的Request去请求缩略图
private void loadImageThumbnailRequest() { // setup Glide request without the into() methodDrawableRequestBuilder<String> thumbnailRequest = Glide.with( context ).load( thumbnailUrl );// pass the request as a a parameter to the thumbnail requestGlide.with( context ).load( UsageExampleGifAndVideos.gifUrl ).thumbnail( thumbnailRequest ).into( imageView);
}
将图片显示在普通View上:
public <T> void showImageOnCustomView(T t, String url, View view) {ViewTarget viewTarget = new ViewTarget<View, GlideDrawable>(view) {@Overridepublic void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {//>=API 16 this.view.setBackground(resource.getCurrent());this.view.setBackgroundDrawable(resource.getCurrent());}};Glide.with(context).load(url).into(viewTarget);}
属性动画animate(): 给图片添加动画,比如属性动画 translate、scale、alpha、rotate,又或者 Activity切换样式 这种属性动画 android.R.anim.slide_in_left
Glide .with( context ).load( url ).animate( android.R.anim.slide_in_left ) // or R.anim.zoom_in.into( imageView1 );
也可以自定义xml Animation。
或者:
ViewPropertyAnimation.Animator animationObject = new ViewPropertyAnimation.Animator() { @Overridepublic void animate(View view) {// if it's a custom view class, cast it here// then find subviews and do the animations// here, we just use the entire view for the fade animationview.setAlpha( 0f );ObjectAnimator fadeAnim = ObjectAnimator.ofFloat( view, "alpha", 0f, 1f );fadeAnim.setDuration( 2500 );fadeAnim.start();}
};Glide .with( context ).load( url ).animate( animationObject ).into( imageView );
图片进行转换transform() /bitmapTransform(): 比如模糊,圆形图片 and so on。
public class BlurTransformation extends BitmapTransformation {private RenderScript rs;public BlurTransformation(Context context) {super( context );rs = RenderScript.create( context );}@Overrideprotected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {Bitmap blurredBitmap = toTransform.copy( Bitmap.Config.ARGB_8888, true );// Allocate memory for Renderscript to work withAllocation input = Allocation.createFromBitmap(rs, blurredBitmap, Allocation.MipmapControl.MIPMAP_FULL, Allocation.USAGE_SHARED);Allocation output = Allocation.createTyped(rs, input.getType());// Load up an instance of the specific script that we want to use.ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));script.setInput(input);// Set the blur radiusscript.setRadius(10);// Start the ScriptIntrinisicBlurscript.forEach(output);// Copy the output to the blurred bitmapoutput.copyTo(blurredBitmap);toTransform.recycle();return blurredBitmap;}@Overridepublic String getId() {return "blur";}
}Glide .with( context ).load( url ).transform( new BlurTransformation( context ) )//.bitmapTransform( new BlurTransformation( context ) ) // this would work too!.into( imageView);
自定义Glide组件GlideModule 配置
/*** Instruction :设置 MemoryCache BitmapPool DiskCache size or path&size* Created by zhangjun on 2016-8-19 17:24*/
public class CustomCachingGlideModule implements GlideModule {@Overridepublic void applyOptions(Context context, GlideBuilder builder) {MemorySizeCalculator calculator = new MemorySizeCalculator(context);int defaultMemoryCacheSize = calculator.getMemoryCacheSize();int defaultBitmapPoolSize = calculator.getBitmapPoolSize();int customMemoryCacheSize = (int) (2 * defaultMemoryCacheSize);int customBitmapPoolSize = (int) (2 * defaultBitmapPoolSize);builder.setMemoryCache(new LruResourceCache(customMemoryCacheSize));builder.setBitmapPool(new LruBitmapPool( customBitmapPoolSize) );int cacheSize100MegaBytes = 104857600;Log.e("CustomCachingGlide","32");
// builder.setDiskCache(// 内部
// new InternalCacheDiskCacheFactory(context, cacheSize100MegaBytes)//外部
// new ExternalCacheDiskCacheFactory(context,cacheSize100MegaBytes)
// );//builder.setDiskCache(alCacheDiskCacheFactory(context, cacheSize100MegaBytes));//new Extern// or any other path
// String downloadDirectoryPath = Environment.getDownloadCacheDirectory().getPath();
// String downloadDirectoryPath= Environment.getExternalStorageDirectory().getPath();String downloadDirectoryPath=ApplicationData.getPicDir();Log.e("CustomCachingGlideModule",""+downloadDirectoryPath);Log.e("CustomCachingGlide","downloadDirectoryPat="+downloadDirectoryPath);builder.setDiskCache(new DiskLruCacheFactory( downloadDirectoryPath, cacheSize100MegaBytes) );}@Overridepublic void registerComponents(Context context, Glide glide) {}
}在清单文件中:<meta-dataandroid:name="packageName.CustomCachingGlideModule"android:value="GlideModule" />
设置网络请求库:
Glide 默认用HttpUrlConnetction去请求网络,默认提供几张请求方式 分别是Volley 和OKHttp
使用方式:
Volley在build.gradle:
dependencies { // your other dependencies// ...// Glidecompile 'com.github.bumptech.glide:glide:3.7.0'// Glide's Volley Integration compile 'com.github.bumptech.glide:volley-integration:1.4.0@aar'compile 'com.mcxiaoke.volley:library:1.0.8'
}
OK 在build.gradle:
dependencies { // your other dependencies// ...// Glidecompile 'com.github.bumptech.glide:glide:3.7.0'// Glide's OkHttp3 Integration compile 'com.github.bumptech.glide:okhttp3-integration:1.4.0@aar'compile 'com.squareup.okhttp3:okhttp:3.2.0'
}
下面的作为了解
1.Glide请求Https :
通过创建禁止ssl 验证的OKHttpClient来实现
public class UnsafeOkHttpClient { public static OkHttpClient getUnsafeOkHttpClient() {try {// Create a trust manager that does not validate certificate chainsfinal TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;}}};// Install the all-trusting trust managerfinal SSLContext sslContext = SSLContext.getInstance("SSL");sslContext.init(null, trustAllCerts, new java.security.SecureRandom());// Create an ssl socket factory with our all-trusting managerfinal SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();OkHttpClient okHttpClient = new OkHttpClient();okHttpClient.setSslSocketFactory(sslSocketFactory);okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));okHttpClient.setHostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});return okHttpClient;} catch (Exception e) {throw new RuntimeException(e);}}
}
public class UnsafeOkHttpGlideModule implements GlideModule { @Overridepublic void applyOptions(Context context, GlideBuilder builder) {}@Overridepublic void registerComponents(Context context, Glide glide) {glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory());}}
public class OkHttpUrlLoader implements ModelLoader<GlideUrl, InputStream> {/*** The default factory for {@link OkHttpUrlLoader}s.*/public static class Factory implements ModelLoaderFactory<GlideUrl, InputStream> {private static volatile OkHttpClient internalClient;private OkHttpClient client;private static OkHttpClient getInternalClient() {if (internalClient == null) {synchronized (Factory.class) {if (internalClient == null) {internalClient = UnsafeOkHttpClient.getUnsafeOkHttpClient();}}}return internalClient;}/*** Constructor for a new Factory that runs requests using a static singleton client.*/public Factory() {this(getInternalClient());}/*** Constructor for a new Factory that runs requests using given client.*/public Factory(OkHttpClient client) {this.client = client;}@Overridepublic ModelLoader<GlideUrl, InputStream> build(Context context, GenericLoaderFactory factories) {return new OkHttpUrlLoader(client);}@Overridepublic void teardown() {// Do nothing, this instance doesn't own the client.}}private final OkHttpClient client;public OkHttpUrlLoader(OkHttpClient client) {this.client = client;}@Overridepublic DataFetcher<InputStream> getResourceFetcher(GlideUrl model, int width, int height) {return new OkHttpStreamFetcher(client, model);}
}
public class OkHttpStreamFetcher implements DataFetcher<InputStream> { private final OkHttpClient client;private final GlideUrl url;private InputStream stream;private ResponseBody responseBody;public OkHttpStreamFetcher(OkHttpClient client, GlideUrl url) {this.client = client;this.url = url;}@Overridepublic InputStream loadData(Priority priority) throws Exception {Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {String key = headerEntry.getKey();requestBuilder.addHeader(key, headerEntry.getValue());}Request request = requestBuilder.build();Response response = client.newCall(request).execute();responseBody = response.body();if (!response.isSuccessful()) {throw new IOException("Request failed with code: " + response.code());}long contentLength = responseBody.contentLength();stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);return stream;}@Overridepublic void cleanup() {if (stream != null) {try {stream.close();} catch (IOException e) {// Ignored}}if (responseBody != null) {try {responseBody.close();} catch (IOException e) {// Ignored.}}}@Overridepublic String getId() {return url.getCacheKey();}@Overridepublic void cancel() {// TODO: call cancel on the client when this method is called on a background thread. See #257}
}
2.提供一个工具类。
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ImageView;import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.target.ViewTarget;
import com.bumptech.glide.signature.StringSignature;import java.io.File;import jp.wasabeef.glide.transformations.CropCircleTransformation;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;public class ImageLoaderHelper {static String TAG = "ImageLoaderHelper";private static ImageLoaderHelper instance = new ImageLoaderHelper();/*** 圆角度数*/private static int radius = 20;private ImageLoaderHelper() {}public static ImageLoaderHelper getInstance() {return instance;}/**** 最简单的使用方式 with load into** @param t FragmentActivity、Activity、Fragment、Context或者android.app.Fragment的实例对象。* @param url 本地File、远程Uri或Resources* @param imageView imageView* @param <T>*/public <T> void loadUrlImage(T t, String url, ImageView imageView) {if(imageView!=null&&t !=null){if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(url).into(imageView);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(url).signature(new StringSignature("1")).into(imageView);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(url).into(imageView);} else if (t instanceof Context) {Glide.with((Context) t).load(url).into(imageView);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(url).into(imageView);}}}/**** 加载resource中的Image* @param t FragmentActivity、Activity、Fragment、Context或者android.app.Fragment的实例对象。* @param resourceId 资源图片 id* @param imageView* @param <T>*/public <T> void loadResImage(T t, int resourceId, ImageView imageView) {if(imageView!=null&&t!=null){if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(resourceId).into(imageView);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(resourceId).into(imageView);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(resourceId).into(imageView);} else if (t instanceof Context) {Glide.with((Context) t).load(resourceId).into(imageView);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(resourceId).into(imageView);}}}/*** 带有加载中,加载失败展示图的加载方式* @param t* @param url* @param holderId* @param imageView* @param <T>*/public <T> void loadUrlImage(T t, String url, int holderId, ImageView imageView) {loadUrlImage(t, url, holderId, holderId, imageView);}/**** 带有加载中,加载失败展示图的加载方式** @param t FragmentActivity、Activity、Fragment、Context或者android.app.Fragment的实例对象。* @param url 本地File、远程Uri* @param holderId 占位图 id* @param errorId 加载失败展示图 id* @param imageView* @param <T>*/public <T> void loadUrlImage(T t, String url, int holderId, int errorId, ImageView imageView) {if(imageView!=null&&t !=null) {if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(url).placeholder(holderId).error(errorId).dontAnimate().dontTransform().into(imageView);} else if (t instanceof Activity) {if(((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(url).placeholder(holderId).error(errorId).dontAnimate().dontTransform().into(imageView);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(url).placeholder(holderId).error(errorId).dontAnimate().dontTransform().into(imageView);} else if (t instanceof Context) {Glide.with((Context) t).load(url).placeholder(holderId).error(errorId).dontAnimate().dontTransform().into(imageView);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(url).placeholder(holderId).error(errorId).dontAnimate().into(imageView);}}}/**** 带有加载中,加载失败展示图的加载方式(圆角)** @param t FragmentActivity、Activity、Fragment、Context或者android.app.Fragment的实例对象。* @param url 本地File、远程Uri* @param holderId 占位图 id* @param errorId 加载失败展示图 id* @param imageView* @param <T>*/public <T> void loadUrlImageCorner(T t, String url, int holderId, int errorId, int cornerValue ,ImageView imageView) {if(imageView!=null&&t !=null) {if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(url).crossFade(1000).placeholder(holderId).error(errorId).dontAnimate().dontTransform().bitmapTransform(new RoundedCornersTransformation((FragmentActivity) t, cornerValue, 0, RoundedCornersTransformation.CornerType.ALL)).into(imageView);} else if (t instanceof Activity) {if(((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(url).crossFade(1000).placeholder(holderId).error(errorId).dontAnimate().dontTransform().bitmapTransform(new RoundedCornersTransformation((Activity) t, cornerValue, 0, RoundedCornersTransformation.CornerType.ALL)).into(imageView);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(url).crossFade(1000).placeholder(holderId).error(errorId).dontAnimate().dontTransform().bitmapTransform(new RoundedCornersTransformation(((Fragment) t).getActivity(), cornerValue, 0, RoundedCornersTransformation.CornerType.ALL)).into(imageView);} else if (t instanceof Context) {Glide.with((Context) t).load(url).crossFade(1000).placeholder(holderId).error(errorId).dontAnimate().dontTransform().bitmapTransform(new RoundedCornersTransformation((Context) t, cornerValue, 0, RoundedCornersTransformation.CornerType.ALL)).into(imageView);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(url).crossFade(1000).placeholder(holderId).error(errorId).dontAnimate().bitmapTransform(new RoundedCornersTransformation(((android.app.Fragment) t).getActivity(), cornerValue, 0, RoundedCornersTransformation.CornerType.ALL)).into(imageView);}}}/**** 带有加载中,加载失败展示图的加载方式(将图片展示为圆图)** @param t FragmentActivity、Activity、Fragment、Context或者android.app.Fragment的实例对象。* @param url 本地File、远程Uri* @param holderId 占位图 id* @param errorId 加载失败展示图 id* @param imageView* @param <T>*/public <T> void loadUrlImageCircle(T t, String url, int holderId, int errorId, ImageView imageView) {if(imageView!=null&&t !=null) {if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(url).crossFade(1000).placeholder(holderId).error(errorId).dontAnimate().dontTransform().bitmapTransform(new CropCircleTransformation((FragmentActivity) t)).into(imageView);} else if (t instanceof Activity) {if(((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(url).crossFade(1000).placeholder(holderId).error(errorId).dontAnimate().dontTransform().bitmapTransform(new CropCircleTransformation((Activity) t)).into(imageView);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(url).crossFade(1000).placeholder(holderId).error(errorId).dontAnimate().dontTransform().bitmapTransform(new CropCircleTransformation(((Fragment) t).getActivity())).into(imageView);} else if (t instanceof Context) {Glide.with((Context) t).load(url).crossFade(1000).placeholder(holderId).error(errorId).dontAnimate().dontTransform().bitmapTransform(new CropCircleTransformation((Context) t)).into(imageView);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(url).crossFade(1000).placeholder(holderId).error(errorId).dontAnimate().bitmapTransform(new CropCircleTransformation(((android.app.Fragment) t).getActivity())).into(imageView);}}}/**** 带有加载中,加载失败展示图的加载方式(不缓存硬盘,商品标签专用)** @param t FragmentActivity、Activity、Fragment、Context或者android.app.Fragment的实例对象。* @param url 本地File、远程Uri* @param holderId 占位图 id* @param errorId 加载失败展示图 id* @param imageView* @param <T>*/public <T> void loadUrlImageProductTag(T t, String url, int holderId, int errorId, ImageView imageView) {if(imageView!=null&&t!=null){if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(url).placeholder(holderId).error(errorId).dontAnimate().dontTransform().diskCacheStrategy( DiskCacheStrategy.NONE ).into(imageView);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(url).placeholder(holderId).error(errorId).dontAnimate().dontTransform().diskCacheStrategy( DiskCacheStrategy.NONE ).into(imageView);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(url).placeholder(holderId).error(errorId).dontAnimate().dontTransform().diskCacheStrategy( DiskCacheStrategy.NONE ).into(imageView);} else if (t instanceof Context) {Glide.with((Context) t).load(url).placeholder(holderId).error(errorId).dontAnimate().dontTransform().diskCacheStrategy( DiskCacheStrategy.NONE ).into(imageView);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(url).placeholder(holderId).error(errorId).dontAnimate().diskCacheStrategy( DiskCacheStrategy.NONE ).into(imageView);}}}/**** 带有加载中,加载失败展示图的加载方式** @param t FragmentActivity、Activity、Fragment、Context或者android.app.Fragment的实例对象。* @param file 本地File、远程Uri* @param holderId 占位图 id* @param errorId 加载失败展示图 id* @param imageView* @param <T>*/public <T> void loadUrlImage(T t, File file, int holderId, int errorId, ImageView imageView) {if(imageView!=null&&t!=null) {if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(file).placeholder(holderId).error(errorId).dontAnimate().dontTransform().into(imageView);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(file).placeholder(holderId).error(errorId).dontAnimate().dontTransform().into(imageView);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(file).placeholder(holderId).error(errorId).dontAnimate().dontTransform().into(imageView);} else if (t instanceof Context) {Glide.with((Context) t).load(file).placeholder(holderId).error(errorId).dontAnimate().dontTransform().into(imageView);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(file).placeholder(holderId).error(errorId).dontAnimate().into(imageView);}}}/**** 带有加载中,加载失败展示图的加载方式* @param t FragmentActivity、Activity、Fragment、Context或者android.app.Fragment的实例对象。* @param resourceId 资源图片 id* @param holderId 占位图 id* @param errorId 加载失败展示图 id* @param imageView* @param <T>*/public <T> void loadResImage(T t, int resourceId, int holderId, int errorId, ImageView imageView) {if (t instanceof FragmentActivity&&t!=null) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(resourceId).placeholder(holderId).error(errorId).into(imageView);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(resourceId).placeholder(holderId).error(errorId).into(imageView);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(resourceId).placeholder(holderId).error(errorId).into(imageView);} else if (t instanceof Context) {Glide.with((Context) t).load(resourceId).placeholder(holderId).error(errorId).into(imageView);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(resourceId).placeholder(holderId).error(errorId).into(imageView);}}/**** 加载图片淡入展示效果,默认300ms* 重载方法 crossFade(int millSeconds):自定义时长* @param t FragmentActivity、Activity、Fragment、Context或者android.app.Fragment的实例对象。* @param url 本地File、远程Uri* @param holderId 占位图 id* @param errorId 加载失败展示图 id* @param imageView* @param <T>*/public <T> void loadUrlImageCrossFade(T t, String url, int holderId, int errorId, ImageView imageView) {if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(url).placeholder(holderId).error(errorId).crossFade().into(imageView);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(url).placeholder(holderId).error(errorId).crossFade().into(imageView);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(url).placeholder(holderId).error(errorId).crossFade().into(imageView);} else if (t instanceof Context) {Glide.with((Context) t).load(url).placeholder(holderId).error(errorId).crossFade().into(imageView);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(url).placeholder(holderId).error(errorId).crossFade().into(imageView);}}/***** @param t FragmentActivity、Activity、Fragment、Context或者android.app.Fragment的实例对象。* @param resourceId 资源图片 id* @param holderId 占位图 id* @param errorId 加载失败展示图 id* @param imageView* @param <T>*/public <T> void loadResImageCrossFade(T t, int resourceId, int holderId, int errorId, ImageView imageView) {if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(resourceId).placeholder(holderId).error(errorId).crossFade().into(imageView);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(resourceId).placeholder(holderId).error(errorId).crossFade().into(imageView);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(resourceId).placeholder(holderId).error(errorId).crossFade().into(imageView);} else if (t instanceof Context) {Glide.with((Context) t).load(resourceId).placeholder(holderId).error(errorId).crossFade().into(imageView);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(resourceId).placeholder(holderId).error(errorId).crossFade().into(imageView);}}/*** 不带任何效果的加载方式** @param t* @param url 本地File、远程Uri或Resources* @param holderId 占位图* @param errorId 加载失败展示图* @param imageView* @param <T>*/public <T> void showImageCancelAnimate(T t, String url, int holderId, int errorId, ImageView imageView) {if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(url).placeholder(holderId).error(errorId).dontAnimate().into(imageView);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(url).placeholder(holderId).error(errorId).dontAnimate().into(imageView);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(url).placeholder(holderId).error(errorId).dontAnimate().into(imageView);} else if (t instanceof Context) {Glide.with((Context) t).load(url).placeholder(holderId).error(errorId).dontAnimate().into(imageView);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(url).placeholder(holderId).error(errorId).dontAnimate().into(imageView);}}/*** 比例扩大图片的size居中显示,Glide默认都是根据ImageView去适应大小的** @param t* @param url* @param holderId* @param errorId* @param imageView* @param <T>*/public <T> void showImageCenterCrop(T t, String url, int holderId, int errorId, ImageView imageView) {if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(url).placeholder(holderId).error(errorId).dontAnimate().centerCrop().into(imageView);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(url).placeholder(holderId).error(errorId).dontAnimate().centerCrop().into(imageView);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(url).placeholder(holderId).error(errorId).dontAnimate().centerCrop().into(imageView);} else if (t instanceof Context) {Glide.with((Context) t).load(url).placeholder(holderId).error(errorId).dontAnimate().centerCrop().into(imageView);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(url).placeholder(holderId).error(errorId).dontAnimate().centerCrop().into(imageView);}}/*** 比例扩大图片的size居中显示,Glide默认都是根据ImageView去适应大小的** @param t* @param url* @param holderId* @param errorId* @param imageView* @param <T>*/public <T> void showImageFitCenter(T t, String url, int holderId, int errorId, ImageView imageView) {if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(url).placeholder(holderId).error(errorId).dontAnimate().fitCenter().into(imageView);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(url).placeholder(holderId).error(errorId).dontAnimate().fitCenter().into(imageView);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(url).placeholder(holderId).error(errorId).dontAnimate().fitCenter().into(imageView);} else if (t instanceof Context) {Glide.with((Context) t).load(url).placeholder(holderId).error(errorId).dontAnimate().fitCenter().into(imageView);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(url).placeholder(holderId).error(errorId).fitCenter().into(imageView);}}/*** 展示第一帧的加载方式,比如GIF** @param t* @param url* @param imageView* @param <T>*/public <T> void showImageAsBitmap(T t, String url, ImageView imageView) {if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(url).asBitmap().into(imageView);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(url).asBitmap().into(imageView);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(url).asBitmap().into(imageView);} else if (t instanceof Context) {Glide.with((Context) t).load(url).asBitmap().into(imageView);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(url).asBitmap().into(imageView);}}/*** 在非ImageView上展示图片** @param t 一般用this即可。* @param url 网络Url* @param view View 对象* @param <T>*/public <T> void showImageOnCustomView(T t, String url, int holderId, int errorId, View view) {ViewTarget viewTarget = new ViewTarget<View, GlideDrawable>(view) {@Overridepublic void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {//>=API 16 this.view.setBackground(resource.getCurrent());this.view.setBackgroundDrawable(resource.getCurrent());}};if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(url).placeholder(holderId).error(errorId).into(viewTarget);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(url).placeholder(holderId).error(errorId).into(viewTarget);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(url).placeholder(holderId).error(errorId).into(viewTarget);} else if (t instanceof Context) {Glide.with((Context) t).load(url).placeholder(holderId).error(errorId).into(viewTarget);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(url).placeholder(holderId).error(errorId).into(viewTarget);}}/*** 在非ImageView上展示图片** @param t 一般用this即可。* @param url 网络Url* @param view View 对象* @param <T>*/public <T> void showImageOnCustomView(T t, String url, View view) {ViewTarget viewTarget = new ViewTarget<View, GlideDrawable>(view) {@Overridepublic void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {//>=API 16 this.view.setBackground(resource.getCurrent());this.view.setBackgroundDrawable(resource.getCurrent());}};if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(url).into(viewTarget);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(url).into(viewTarget);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(url).into(viewTarget);} else if (t instanceof Context) {Glide.with((Context) t).load(url).into(viewTarget);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(url).into(viewTarget);}}/*** 在非ImageView上展示图片** @param t 一般用this即可。* @param url 网络Url* @param holderId 占位图* @param errorId 失败图* @param view View 对象* @param <T>*/public <T> void loadImageOnCustomView(T t, String url, int holderId, int errorId, View view) {ViewTarget viewTarget = new ViewTarget<View, GlideDrawable>(view) {@Overridepublic void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {//>=API 16 this.view.setBackground(resource.getCurrent());this.view.setBackgroundDrawable(resource.getCurrent());}@Overridepublic void onLoadStarted(Drawable placeholder) {super.onLoadStarted(placeholder);this.view.setBackgroundDrawable(placeholder);}@Overridepublic void onLoadFailed(Exception e, Drawable errorDrawable) {super.onLoadFailed(e, errorDrawable);this.view.setBackgroundDrawable(errorDrawable);}};if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(url).placeholder(holderId).error(errorId).into(viewTarget);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(url).placeholder(holderId).error(errorId).into(viewTarget);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(url).placeholder(holderId).error(errorId).into(viewTarget);} else if (t instanceof Context) {Glide.with((Context) t).load(url).placeholder(holderId).error(errorId).into(viewTarget);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(url).placeholder(holderId).error(errorId).into(viewTarget);}}/*** 在非ImageView上展示图片** @param t 一般用this即可。* @param url 网络Url* @param view View 对象* @param <T>*/public <T> void loadImageOnCustomView(T t, String url, View view) {ViewTarget viewTarget = new ViewTarget<View, GlideDrawable>(view) {@Overridepublic void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {//>=API 16 this.view.setBackground(resource.getCurrent());this.view.setBackgroundDrawable(resource.getCurrent());}@Overridepublic void onLoadStarted(Drawable placeholder) {super.onLoadStarted(placeholder);this.view.setBackgroundDrawable(placeholder);}@Overridepublic void onLoadFailed(Exception e, Drawable errorDrawable) {super.onLoadFailed(e, errorDrawable);this.view.setBackgroundDrawable(errorDrawable);}};if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(url).into(viewTarget);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(url).into(viewTarget);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(url).into(viewTarget);} else if (t instanceof Context) {Glide.with((Context) t).load(url).into(viewTarget);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(url).into(viewTarget);}}/*** 在非ImageView上展示图片* @param t 一般用this即可。* @param resourceId resource id* @param view View 对象* @param <T>*/public <T> void loadImageOnCustomView(T t, int resourceId, View view) {ViewTarget viewTarget = new ViewTarget<View, GlideDrawable>(view) {@Overridepublic void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
// this.view.setBackground(resource.getCurrent());this.view.setBackgroundDrawable(resource.getCurrent());}};if (t instanceof FragmentActivity) {if(((FragmentActivity) t).isFinishing()){return;}Glide.with((FragmentActivity) t).load(resourceId).into(viewTarget);} else if (t instanceof Activity) {if(t == null || ((Activity) t).isFinishing()){return;}Glide.with((Activity) t).load(resourceId).into(viewTarget);} else if (t instanceof Fragment) {Glide.with((Fragment) t).load(resourceId).into(viewTarget);} else if (t instanceof Context) {Glide.with((Context) t).load(resourceId).into(viewTarget);} else if (t instanceof android.app.Fragment) {Glide.with((android.app.Fragment) t).load(resourceId).into(viewTarget);}}/**** 加载图片作为背景* 最简单的使用方式 with load into** @param url 本地File、远程Uri或Resources* @param view*/public void loadUrlImageAsBackground(Context context, String url, final View view) {try {Glide.with(context).load(url).asBitmap().into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {@Overridepublic void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {Drawable drawable = new BitmapDrawable(resource);if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {view.setBackground(drawable);}}});} catch (IllegalArgumentException e) {LogUtils.e(e);}}// // 加载drawable圆型图片
// public void loadCircleResImage(Context mContext, int resId, ImageView imageView) {
// Glide.with(mContext)
// .load(resId)
// .crossFade()
// .bitmapTransform(new CropCircleTransformation(mContext))
// .into(imageView);
// }
//
// // 加载本地圆型图片
// public void loadCircleLocalImage(Context mContext, String path, ImageView imageView) {
// Glide.with(mContext)
// .load( path)
// .crossFade()
// .transform(new GlideCircleTransform(mContext))
// .into(imageView);
// }public static final String ANDROID_RESOURCE = "android.resource://";public static final String FILE_SEPARATOR = "/";private Uri resourceIdToUri(String packageName, int resourceId) {return Uri.parse(ANDROID_RESOURCE + packageName + FILE_SEPARATOR + resourceId);}// public static void showLocalThumbnail(Context context,String filePath, ImageView imageView){
// Glide.with(context).load(Uri.fromFile(new File(filePath))).into(imageView);
// }// public static void showImage(Context context, String url, ImageView imageView){
// Glide.with(context).load(url).into(imageView);
// }
// public static void showImage(Activity activity, String url, ImageView imageView){
// Glide.with(activity).load(url).into(imageView);
// }
// public static void showImage(Fragment fragment, String url, ImageView imageView){
// Glide.with(fragment).load(url).into(imageView);
// }
// public static void showImage(android.app.Fragment fragment, String url, ImageView imageView){
// Glide.with(fragment).load(url).into(imageView);
// }
// public static void showImage(FragmentActivity fragmentActivity, String url, ImageView imageView){
// Glide.with(fragmentActivity).load(url).into(imageView);
// }// public static void showImage(Context context, String url,int holderId,int errorId, ImageView imageView){
// Glide.with(context).load(url).placeholder(holderId).error(errorId).into(imageView);
// }
// public static void showImageCrossFade(Context context, String url,int holderId,int errorId, ImageView imageView){
// Glide.with(context).load(url).placeholder(holderId).error(errorId).crossFade().into(imageView);
// }
// public static void showImageCancelAnimate(Context context, String url,int holderId,int errorId, ImageView imageView){
// Glide.with(context).load(url).placeholder(holderId).error(errorId).dontAnimate().into(imageView);
// }
// public static void showImageCenterCrop(Context context, String url,int holderId,int errorId, ImageView imageView){
// Glide.with(context).load(url).placeholder(holderId).error(errorId).dontAnimate().centerCrop().into(imageView);
// }// public static void showImageAsBitmap(Context context,String url, ImageView imageView){
// Glide.with(context).load(url).asBitmap().into(imageView);
// }// public static void showLocalThumbnail(Context context,String filePath, ImageView imageView){
// Glide.with(context).load(Uri.fromFile(new File(filePath))).into(imageView);
// }}
谢谢认真观读本文的每一位小伙伴,衷心欢迎小伙伴给我指出文中的错误,也欢迎小伙伴与我交流学习。
欢迎爱学习的小伙伴加群一起进步:230274309 。
这篇关于(源码分析)Glide(图片异步加载缓存库)的方法介绍(附封装的工具类)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!