1:Picasso.with(context)
.load(imageURL)
.resize(parent.getWidth(),0)
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(holder.image);
picasso.setIndicatorsEnabled(true); 可以设置,如果是从网络或者本地,或者内存,在图片的左上角有不通过的标志
如果出现Transformation key must not be null.的错误,是因为下面的方法返回了null;
public String key() { return "circle"; }
还可以修改Picasso的一些配置,例如缓存的大小和缓存的位置:
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); Picasso picasso = new Picasso.Builder(this) .memoryCache(new LruCache(10 << 20))//内存缓存的大小为10MB .downloader(new OkHttpDownloader(getCacheDir(),30<<20))//磁盘缓存,缓存大小为30MB .defaultBitmapConfig(Bitmap.Config.RGB_565)//Bitmap.Config.ARGB_8888 .build();picasso.setIndicatorsEnabled(true); 可以设置,如果是从网络或者本地,或者内存,在图片的左上角有不通过的标志
Picasso.setSingletonInstance(picasso); }}
转载:
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/0731/1639.html
picasso-强大的Android图片下载缓存库
1
|
|
Api看起来非常独特,是吧。
Picasso不仅实现了图片异步加载的功能,还解决了android中加载图片时需要解决的一些常见问题:
1.在adapter中需要取消已经不在视野范围的ImageView图片资源的加载,否则会导致图片错位,Picasso已经解决了这个问题。
2.使用复杂的图片压缩转换来尽可能的减少内存消耗
3.自带内存和硬盘二级缓存功能
特性以及示例代码:
ADAPTER 中的下载:Adapter的重用会被自动检测到,Picasso会取消上次的加载
1
2
3
4
5
6
7
8
|
@Override public void getView(int position, View convertView, ViewGroup parent) {
SquaredImageView view = (SquaredImageView) convertView;
if
(view ==
null
) {
view =
new
SquaredImageView(context);
}
String url = getItem(position);
Picasso.
with
(context).load(url).into(view);
}
|
图片转换:转换图片以适应布局大小并减少内存占用
1
2
3
4
5
|
Picasso.
with
(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView);
|
你还可以自定义转换:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class CropSquareTransformation implements Transformation {
@Override public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
if
(result != source) {
source.recycle();
}
return
result;
}
@Override public String key() {
return
"square()"
; }
}
|
将CropSquareTransformation 的对象传递给transform 方法即可。
Place holders-空白或者错误占位图片:picasso提供了两种占位图片,未加载完成或者加载发生错误的时需要一张图片作为提示。
1
2
3
4
5
|
Picasso.
with
(context)
.load(url)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(imageView);
|
如果加载发生错误会重复三次请求,三次都失败才会显示erro Place holder
资源文件的加载:除了加载网络图片picasso还支持加载Resources, assets, files, content providers中的资源文件。
1
2
|
Picasso.
with
(context).load(R.drawable.landing_screen).into(imageView1);
Picasso.
with
(context).load(
new
File(...)).into(imageView2);
|
下面是picasso源码的解析(不看不影响使用)
Cache,缓存类
1
|
this
.map =
new
LinkedHashMap<String, Bitmap>(0, 0.75f,
true
);
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
private void trimToSize(int maxSize) {
while
(
true
) {
String key;
Bitmap value;
synchronized (
this
) {
if
(size < 0 || (map.isEmpty() && size != 0)) {
throw
new
IllegalStateException(getClass().getName()
+
".sizeOf() is reporting inconsistent results!"
);
}
if
(size <= maxSize || map.isEmpty()) {
break
;
}
Map.Entry<String, Bitmap> toEvict = map.entrySet().iterator()
.next();
key = toEvict.getKey();
value = toEvict.getValue();
map.remove(key);
size -= Utils.getBitmapBytes(value);
evictionCount++;
}
}
}
|
Request,操作封装类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public interface Transformation {
/**
* Transform the source bitmap into a new bitmap. If you create a new bitmap instance, you must
* call {@link android.graphics.Bitmap#recycle()} on {@code source}. You may return the original
* if no transformation is required.
*/
Bitmap transform(Bitmap source);
/**
* Returns a unique key for the transformation, used for caching purposes. If the transformation
* has parameters (e.g. size, scale factor, etc) then these should be part of the key.
*/
String key();
}
|
当操作封装好以后,会将Request传到另一个结构中Action。
Action
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@Override
public void complete(Bitmap result, Picasso.LoadedFrom from) {
if
(result ==
null
) {
throw
new
AssertionError(String.format(
"Attempted to complete action with no result!\n%s"
,
this
));
}
ImageView target =
this
.target.get();
if
(target ==
null
) {
return
;
}
Context context = picasso.context;
boolean debugging = picasso.debugging;
PicassoDrawable.setBitmap(target, context, result, from, noFade,
debugging);
if
(callback !=
null
) {
callback.onSuccess();
}
}
|
有了加载任务,具体的图片下载与解析是在哪里呢?这些都是耗时的操作,应该放在异步线程中进行,就是下面的BitmapHunter。
BitmapHunter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
@Override
public void run() {
try
{
Thread.currentThread()
.setName(Utils.THREAD_PREFIX + data.getName());
result = hunt();
if
(result ==
null
) {
dispatcher.dispatchFailed(
this
);
}
else
{
dispatcher.dispatchComplete(
this
);
}
}
catch
(IOException e) {
exception = e;
dispatcher.dispatchRetry(
this
);
}
catch
(Exception e) {
exception = e;
dispatcher.dispatchFailed(
this
);
} finally {
Thread.currentThread().setName(Utils.THREAD_IDLE_NAME);
}
}
abstract Bitmap decode(Request data) throws IOException;
Bitmap hunt() throws IOException {
Bitmap bitmap;
if
(!skipMemoryCache) {
bitmap = cache.get(key);
if
(bitmap !=
null
) {
stats.dispatchCacheHit();
loadedFrom = MEMORY;
return
bitmap;
}
}
bitmap = decode(data);
if
(bitmap !=
null
) {
stats.dispatchBitmapDecoded(bitmap);
if
(data.needsTransformation() || exifRotation != 0) {
synchronized (DECODE_LOCK) {
if
(data.needsMatrixTransform() || exifRotation != 0) {
bitmap = transformResult(data, bitmap, exifRotation);
}
if
(data.hasCustomTransformations()) {
bitmap = applyCustomTransformations(
data.transformations, bitmap);
}
}
stats.dispatchBitmapTransformed(bitmap);
}
}
return
bitmap;
}
|
Dispatcher任务调度器
外部调用的是dispatchXXX方法,然后通过handler将请求转换到对应的performXXX方法。
例如生成Action以后就会调用dispather的dispatchSubmit()来请求执行,
1
2
3
|
void dispatchSubmit(Action action) {
handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
}
|
handler接到消息后转换到performSubmit方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
void performSubmit(Action action) {
BitmapHunter hunter = hunterMap.get(action.getKey());
if
(hunter !=
null
) {
hunter.attach(action);
return
;
}
if
(service.isShutdown()) {
return
;
}
hunter = forRequest(context, action.getPicasso(),
this
, cache, stats,
action, downloader);
hunter.future = service.submit(hunter);
hunterMap.put(action.getKey(), hunter);
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
public static Picasso
with
(Context context) {
if
(singleton ==
null
) {
singleton =
new
Builder(context).build();
}
return
singleton;
}
public Picasso build() {
Context context =
this
.context;
if
(downloader ==
null
) {
downloader = Utils.createDefaultDownloader(context);
}
if
(cache ==
null
) {
cache =
new
LruCache(context);
}
if
(service ==
null
) {
service =
new
PicassoExecutorService();
}
if
(transformer ==
null
) {
transformer = RequestTransformer.IDENTITY;
}
Stats stats =
new
Stats(cache);
Dispatcher dispatcher =
new
Dispatcher(context, service, HANDLER,
downloader, cache, stats);
return
new
Picasso(context, dispatcher, cache, listener,
transformer, stats, debugging);
}
|
在Picasso.with()的时候会将执行所需的所有必备元素创建出来,如缓存cache、执行executorService、调度dispatch等,在load()时创建Request,在into()中创建action、bitmapHunter,并最终交给dispatcher执行。
if(item.getImage()==null){
holder.image.setVisibility(View.GONE);}else{
holder.image.setVisibility(View.VISIBLE);
String imageURL = getImageURL(item.getImage());
Picasso.with(context).load(imageURL).into(holder.image);
}
public static String getImageURL(String image){
String url = "http://pic.qiushibaike.com/system/pictures/%s/%s/%s/%s";
Pattern pattern = Pattern.compile("(\\d+)\\d{4}");
Matcher matcher = pattern.matcher(image);
matcher.find();
Log.d("151229MY", "getImageURL: " + matcher.group());
return String.format(url, matcher.group(1), matcher.group(), "medium", image);
}
图片也有可能为空:
public Item(JSONObject object) throws JSONException {
if(!object.isNull("user")) {//因为有的是匿名发布的
userIcon = object.getJSONObject("user").getString("icon");
userName = object.getJSONObject("user").getString("login");
}
if(!object.isNull("image")) {
image = object.getString("image");
}
content =object.getString("content");
}
Picaso的resize 不可以同时为0,可以有一个为0,这个0不生效,他会按比例下载
Picasso.with(context)
.load(imageURL)
.resize(parent.getWidth(),0)//parent就是listView ,就是listView的宽度,现在就会匹配宽度了。
.into(holder.image);
还有一种在listView 里面不太好用,但是在其他里面可以用的
就是fit()
还有属性就是centerInside(),居中适应大小
centerCrop剪切中间的部分。
还有下载中和下载失败的,
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
Picasso.with(context)
.load(imageURL)
.resize(parent.getWidth(),0)
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(holder.image);
在Item里面添加添加id
public Item(JSONObject object) throws JSONException {
if(!object.isNull("user")) {//因为有的是匿名发布的
userIcon = object.getJSONObject("user").getString("icon");
userName = object.getJSONObject("user").getString("login");
userId= object.getJSONObject("user").getLong("id");
}
if(!object.isNull("image")) {
image = object.getString("image");
}
content =object.getString("content");
}
public static String getIconURL(long id, String icon){
String url = "http://pic.qiushibaike.com/system/avtnew/%s/%s/thumb/%s";
return String.format(url, id / 10000, id, icon);
}
在下面添加Picasso
if(item.getUserName()!=null) {
holder.name.setText(item.getUserName());
Picasso.with(context).load(getIconURL(item.getUserId(),item.getUserIcon())).into(holder.icon);
}