闲来无事,今天又重新打开了UniversalImageLoader源码,以下简称为UIL。
由于前几天做了一个基于SDK开发的项目,也就是给第三开发者用到的一个Library库。所以就打开了UIL源码用到的自己封装的库源码,来看下他们是怎么封装的,要来学习一下。
一、先来po一张图。
因为UIL库主要作用是用一款图片加载引擎库。所以涉及到图片核心操作代码core包,下载完毕图片一定是要进行缓存的,进行性能优化,所以添加了一个cache包,最后就是一些使用到的工具类了再添加一个utils包。
二、在我们开发过程中有可能会遇到这样的需求,就是通过一个字符串传给一个方法最后返回一个类型,这个类型就可以知道是什么东西了
之前我们的做法可能都是If else 然后把传过来的字符串进行匹配最后返回一个想要的类型。现在看UIL是怎么实现的
UIL需求:传入一个字符串返回是http https file 或者更多
调用方式是这样的
String uri = "http://image.com/1.png";
Scheme result = Scheme.ofUri(uri);
Scheme expected = Scheme.HTTP;
Assertions.assertThat(result).isEqualTo(expected);
他是通过一个Scheme内部类的ofUril方法最后返回Scheme
public interface ImageDownloader {
/**
* Retrieves {@link InputStream} of image by URI.
*
* @param imageUri Image URI
* @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
* DisplayImageOptions.extraForDownloader(Object)}; can be null
* @return {@link InputStream} of image
* @throws IOException if some I/O error occurs during getting image stream
* @throws UnsupportedOperationException if image URI has unsupported scheme(protocol)
*/
InputStream getStream(String imageUri, Object extra) throws IOException;
/** Represents supported schemes(protocols) of URI. Provides convenient methods for work with schemes and URIs. */
public enum Scheme {
HTTP("http"), HTTPS("https"), FILE("file"), CONTENT("content"), ASSETS("assets"), DRAWABLE("drawable"), UNKNOWN("");
private String scheme;
private String uriPrefix;
Scheme(String scheme) {
this.scheme = scheme;
uriPrefix = scheme + "://";
}
/**
* Defines scheme of incoming URI
*
* @param uri URI for scheme detection
* @return Scheme of incoming URI
*/
public static Scheme ofUri(String uri) {
if (uri != null) {
for (Scheme s : values()) {
if (s.belongsTo(uri)) {
return s;
}
}
}
return UNKNOWN;
}
private boolean belongsTo(String uri) {
return uri.toLowerCase(Locale.US).startsWith(uriPrefix);
}
/** Appends scheme to incoming path */
public String wrap(String path) {
return uriPrefix + path;
}
/** Removed scheme part ("scheme://") from incoming URI */
public String crop(String uri) {
if (!belongsTo(uri)) {
throw new IllegalArgumentException(String.format("URI [%1$s] doesn't have expected scheme [%2$s]", uri, scheme));
}
return uri.substring(uriPrefix.length());
}
}
}
通过枚举内部类来遍历,然后通过belongsTo方法来判断是否是想要的值
2.该内部类还有一个方法wrap方法,使用如下:Scheme.FILE.wrap(targetFile.getAbsolutePath())通过此方法只需要传入本地路径,就直接能得出file://+...这样的图片路径,是不是很方便。好了,今天就先分享到这里,我们下期再见