SDWebImage-图片自动缓存、异步加载实用库(转贴)

SDWebImage是一个可以自动管理图片加载的类库。

因为大家都知道,图片加载非常耗流量,所以在移动平台上对于图片的处理就要异常小心了。因此就必须用到本地缓存了。

而我之前写的一个小型App,因为每张图片的名字都是GUID生成的,不会被修改了。所以会每次都检查一下本地是否有这个文件名的文件存在了。这样最大限度的减小了网络流量,不需要每次都加载一次。

不过呢,SDWebImage的功能不仅仅仅限于此,功能更为强大。最基本的有一个UIImageView的category,用法很简单
[imageView setImageWithURL:[NSURLURLWithString:@"http://www.ioslib.com/ioslib.png"]];
另外呢,还有一个SDWebImageManager,使用它可以进行一些异步加载的工作,关于这部分内容,可以参见官方的文档:

https://github.com/rs/SDWebImage#readme

SDWebImage是托管在Github上的:http://github.com/rs/SDWebImage

SDWebImage——简化网络图片处理

用SDWebImage调用网站上的图片,跟本地调用内置在应用包里的图片一样简单。操作也很简单,举例说明

 

Using UIImageView+WebCache category with UITableView

Just #import the UIImageView+WebCache.h header, and call the setImageWithURL:placeholderImage:method from the tableView:cellForRowAtIndexPath: UITableViewDataSource method. Everything will behandled for you, from async downloads to caching management.

#import "UIImageView+WebCache.h"

...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier = @"MyIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:MyIdentifier] autorelease];
    }

    // Here we use the new provided setImageWithURL: method to load the web image
    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    cell.textLabel.text = @"My Text";
    return cell;
}

Using SDWebImageManager

The SDWebImageManager is the class behind the UIImageView+WebCache category. It ties theasynchronous downloader with the image cache store. You can use this classe directly to benefitsfrom web image downloading with caching in another context than a UIView (ie: with Cocos).

Here is a simple example of how to use SDWebImageManager:

SDWebImageManager *manager = [SDWebImageManager sharedManager];

UIImage *cachedImage = [manager imageWithURL:url];

if (cachedImage)
{
    // Use the cached image immediatly
}
else
{
    // Start an async download
    [manager downloadWithURL:url delegate:self];
}

Your class will have to implement the SDWebImageManagerDelegate protocol, and to implement thewebImageManager:didFinishWithImage: method from this protocol:

- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image
{
    // Do something with the downloaded image
}

Using Asynchronous Image Downloader Independently

It is possible to use the async image downloader independently. You just have to create an instanceof SDWebImageDownloader using its convenience constructor downloaderWithURL:delegate:.

downloader = [SDWebImageDownloader downloaderWithURL:url delegate:self];

The download will start immediately and the imageDownloader:didFinishWithImage: method from theSDWebImageDownloaderDelegate protocol will be called as soon as the download of image is completed.

Using Asynchronous Image Caching Independently

It is also possible to use the NSOperation based image cache store independently. SDImageCachemaintains a memory cache and an optional disk cache. Disk cache write operations are performedasynchronous so it doesn't add unnecessary latency to the UI.

The SDImageCache class provides a singleton instance for convenience but you can create your owninstance if you want to create separated cache namespaces.

To lookup the cache, you use the imageForKey: method. If the method returns nil, it means the cachedoesn't currently own the image. You are thus responsible of generating and caching it. The cachekey is an application unique identifier for the image to cache. It is generally the absolute URL ofthe image.

UIImage *myCachedImage = [[SDImageCache sharedImageCache] imageFromKey:myCacheKey];

By default SDImageCache will lookup the disk cache if an image can't be found in the memory cache.You can prevent this from happening by calling the alternative method imageFromKey:fromDisk: with anegative second argument.

To store an image into the cache, you use the storeImage:forKey: method:

[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];

By default, the image will be stored in memory cache as well as on disk cache (asynchronously). Ifyou want only the memory cache, use the alternative method storeImage:forKey:toDisk: with a negativethird argument.



转自 http://www.isdada.com/sdwebimage.html 

偶然所得,不敢独享,与大家分享之~

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用 ListView 异步加载图片时,可以通过以下步骤实现: 1. 创建一个自定义的适配器(Adapter)类,继承自 BaseAdapter。这个适配器将负责管理数据和视图的绑定。 2. 在适配器中,创建一个内部类 ViewHolder,用于保存列表项中的视图引用。这个类将包含一个 ImageView 用于显示图片。 3. 在适配器的 getView 方法中,获取当前列表项的数据,并更新 ViewHolder 中的 ImageView。 4. 在更新 ImageView 时,可以使用异步加载图片的第三方,如 Glide 或 Picasso。这些提供了简单的接口来加载网络图片,并且处理了图片缓存和压缩等问题。 下面是一个简单的示例代码: ```java public class CustomAdapter extends BaseAdapter { private List<String> imageUrlList; private Context context; public CustomAdapter(Context context, List<String> imageUrlList) { this.context = context; this.imageUrlList = imageUrlList; } @Override public int getCount() { return imageUrlList.size(); } @Override public Object getItem(int position) { return imageUrlList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false); viewHolder = new ViewHolder(); viewHolder.imageView = convertView.findViewById(R.id.image_view); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } String imageUrl = imageUrlList.get(position); // 使用 Glide 异步加载图片 Glide.with(context) .load(imageUrl) .placeholder(R.drawable.placeholder_image) // 加载中显示的占位图 .error(R.drawable.error_image) // 加载失败显示的错误图 .into(viewHolder.imageView); return convertView; } static class ViewHolder { ImageView imageView; } } ``` 在上述示例代码中,CustomAdapter 是自定义的适配器类,其中的 getView 方法中使用了 Glide 来异步加载图片。你可以将 imageUrlList 替换为你自己的图片地址列表,并根据需要修改加载中和加载失败时显示的图片资源。同时,记得在布局文件中定义好 ImageView 的 id。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值