Picasso——针对Android的一个强大的图像下载和缓存库

来源:互联网 发布:手机视频软件免费 编辑:程序博客网 时间:2024/04/30 02:19
简介
图片为安卓应用添加了必备内容和视觉风格。Picasso允许应用程序加载图片——往往只需一行代码!
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Picasso会自动处理安卓加载图片时出现的许多常见缺陷:
1.在适配器中处理ImageView循环和下载取消。
2.保证最小内存使用率情况下的复杂图片转换。
3.自动内存和磁盘高速缓存。

特性
适配器下载
可以自动检测适配器复用
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. @Override public void getView(int position, View convertView, ViewGroup parent) {  
  2.    
  3.   SquaredImageView view = (SquaredImageView) convertView;  
  4.    
  5.   if (view == null) {  
  6.      view = new SquaredImageView(context);  
  7.   }  
  8.    
  9.   String url = getItem(position);  
  10.   Picasso.with(context).load(url).into(view);  
  11.    
  12. }  
 
图像变换
变换图像可以更好地适应布局,并且减少内存大小。
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Picasso.with(context)  
  2.   .load(url)  
  3.   .resize(5050)  
  4.   .centerCrop()  
  5.   .into(imageView)  

可以指定自定义变化以便达到更好效果。
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class CropSquareTransformation implements Transformation {  
  2.    
  3.   @Override public Bitmap transform(Bitmap source) {  
  4.    
  5.     int size = Math.min(source.getWidth(), source.getHeight());  
  6.    
  7.     int x = (source.getWidth() - size) / 2;  
  8.    
  9.     int y = (source.getHeight() - size) / 2;  
  10.    
  11.     Bitmap result = Bitmap.createBitmap(source, x, y, size, size);  
  12.    
  13.     if (result != source) {  
  14.    
  15.       source.recycle();  
  16.    
  17.     }  
  18.    
  19.     return result;  
  20.    
  21.   }  
  22.    
  23.   
  24.   @Override public String key() { return "square()"; }  
  25.    
  26. }  
把该类的实例传递给变换方法。


占位符
Picasso把下载和错误占位符作为可选功能。
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Picasso.with(context)  
  2.     .load(url)  
  3.     .placeholder(R.drawable.user_placeholder)  
  4.     .error(R.drawable.user_placeholder_error)  
  5.     .into(imageView);  

在显示错误占位符前请求会重试三次。
 
 
资源加载
资源,资产,文件,内容供应商均可作为图像源。
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);  
  2.    
  3. Picasso.with(context).load(new File(...)).into(imageView2);  
  4.    

DEBUG指标
开发时可以启用彩带来指示图像源。在Picasso实例中调用setIndicatorsEnabled(true)。

Download
picasso-2.4.0.jar(112.05 KB, 下载次数: 14)


[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. MAVEN  
  2.    
  3. <dependency>  
  4.    
  5.   <groupId>com.squareup.picasso</groupId>  
  6.    
  7.   <artifactId>picasso</artifactId>  
  8.    
  9.   <version>2.4.0</version>  
  10.    
  11. </dependency>  

0 0
原创粉丝点击