# [翻译] AsyncImageView 异步下载图片

+关注继续查看

AsyncImageView

https://github.com/nicklockwood/AsyncImageView

AsyncImageView is a simple extension of UIImageView for loading and displaying images asynchronously on iOS so that they do not lock up the UI.

AsyncImageView是关于UIImageView的扩展，用来异步加载和显示图片防止阻塞UI。

## Purpose（目的）

AsyncImageView includes both a simple category on UIImageView for loading and displaying images asynchronously on iOS so that they do not lock up the UI, and a UIImageView subclass for more advanced features. AsyncImageView works with URLs so it can be used with either local or remote files.

Loaded/downloaded images are cached in memory and are automatically cleaned up in the event of a memory warning. The AsyncImageView operates independently of the UIImage cache, but by default any images located in the root of the application bundle will be stored in the UIImage cache instead, avoiding any duplication of cached images.

AsyncImageView包含了两种类型，一种是UIImageView的类目，用来异步加载以及显示图片的。另一种是UIImageView的子类，含有更多的一些特性。AsyncImageView 通过URL来工作，所以，既可以是本地的图片，也可以是网络上的图片。加载和下载图片是缓存在内存的，所以当出现内存警告时会自动删除内存中的图片。AsyncImageView 独立于UIImage的缓存操作，但是默认的是，任何在bundle中的图片都被缓存起来了，防止重复的缓存图片。

## Supported OS & SDK Versions（支持OS&SDK的版本）

• Supported build target - iOS 7.1 (Xcode 5.1, Apple LLVM compiler 5.1)
• Earliest supported deployment target - iOS 5.0
• Earliest compatible deployment target - iOS 4.3
• 支持iOS 7.1
• 支持早期的 iOS 5.0
• 兼容更早期的 iOS 4.3

NOTE: 'Supported' means that the library has been tested with this version. 'Compatible' means that the library should work on this iOS version (i.e. it doesn't rely on any unavailable SDK features) but is no longer being tested for compatibility and may require tweaking or bug fixes to run correctly.

## ARC Compatibility（ARC情况）

As of version 1.5, AsyncImageView requires ARC. If you wish to use AsyncImageView in a non-ARC project, just add the -fobjc-arc compiler flag to the AsyncImageView.m file. To do this, go to the Build Phases tab in your target settings, open the Compile Sources group, double-click AsyncImageView.m in the list and type -fobjc-arc into the popover.

If you wish to convert your whole project to ARC, comment out the #error line in AsyncImageView.m, then run the Edit > Refactor > Convert to Objective-C ARC... tool in Xcode and make sure all files that you wish to use ARC for (including AsyncImageView.m) are checked.

AsyncImageView uses threading internally, but none of the AsyncImageView external interfaces are thread safe, and you should not call any methods or set any properties on any of the AsyncImageView classes except on the main thread.

AsyncImageView 本质上使用了线程，但没有哪个AsyncImageView是线程安全的，你不能设置任何的相关线程的属性，除非在主线程上。

## Installation（安装）

To use the AsyncImageView in an app, just drag the AsyncImageView class files into your project.

## Categories（类目文件）

The basic interface of AsyncImageView is a category that extends UIImageView with the following property:

AsyncImageView 最主要的接口是扩展了一个属性（扩展了一个属性？？？？？

@property (nonatomic, strong) NSURL *imageURL;


This means that you can, for example, set a UIImageView to load a small thumbnail image and then immediately set it to load a larger image and the thumbnail image will still be loaded and set before the larger image loads.

If you access this property it will return the most recent image URL set for the UIImageView, which may not be the next one to be loaded if several image URLs have been queued on that image view. If you wish to cancel the previously loading image, use the -cancelLoadingURL:target: method on the AsyncImageLoader class, passing the UIImageView instance as the target (see below).

## Classes（类）

AsyncImageView includes an AsyncImageView class, which is a subclass of UIImageView. This implements some useful features on top of the UIImageView category, including the automatic display of a loading spinner, and a nice crossfade effect when the image loads.

AsyncImageView库包含了一个AsyncImageView的类,它继承至UIImageView.这个类实现了很多有用的特性,如自动显示一个加载的指示器,以及当图片下载完成后加载时会出现一个渐隐出现的效果.

## AsyncImageView properties（相关属性）

The AsyncImageView class has the following properties:

AsyncImageView有着如下的一些属性:

@property (nonatomic, assign) BOOL showActivityIndicator;


If YES, the AsyncImageView will display a loading spinner when the imageURL is set. This will automatically hide once the image has loaded. Note that this value should bet set before setting the imageURL. Setting this value when loading is already in progress will have no effect. Defaults to YES.

@property (nonatomic, assign) UIActivityIndicatorViewStyle activityIndicatorStyle;


The style that will be used for the UIActivityIndicator (if enabled). Note that this value should bet set beforesetting the imageURL. Setting this value when loading is already in progress will cause the spinner to disappear.

@property (nonatomic, assign) NSTimeInterval crossfadeDuration;


The crossfade animation duration, in seconds. If value is greater than 0, the image will crossfade in once it loads instead of appearing suddenly. Defaults to 0.4.

AsyncImageLoadDidFinish


This fires when an image has been loaded. The notification object contains the target object that loaded the image file (e.g. the UIImageView) and the userInfo dictionary contains the following keys:

• AsyncImageImageKey

• AsyncImageURLKey

The NSURL that the image was loaded from.

• AsyncImageCacheKey

The NSCache that the image was stored in.

AsyncImageLoadDidFail


This fires when an image did not load due to an error. The notification object contains the target object that attempted to load the image file (e.g. the UIImageView) and the userInfo dictionary contains the following keys:

• AsyncImageErrorKey

The NSError generated by the underlying URLConnection.

• AsyncImageURLKey

The NSURL that the image failed to load from.

@property (nonatomic, strong) NSCache *cache;


The cache to be used for image load requests. You can change this value at any time and it will affect all subsequent load requests until it is changed again. By default this is set to [AsyncImageLoader sharedCache]. Set this to nil to disable caching completely, or you can set it to a new NSCache instance or subclass for fine-grained cache control.

@property (nonatomic, assign) NSUInteger concurrentLoads;


@property (nonatomic, assign) NSTimeInterval loadingTimeout;


- (void)loadImageWithURL:(NSURL *)URL target:(id)target success:(SEL)success failure:(SEL)failure;


This queues an image for download. If the queue is empty and the image is already in cache, this will trigger the success action immediately.

The target is retained by the AsyncImageLoader, however the loader will monitor to see if the target is being retained by any other objects, and will release it and terminate the file load if it is not. The target can be nil, in which case the load will still happen as normal and can completion can be detected using the AsyncImageLoadDidFinish and AsyncImageLoadDidFail notifications.

- (void)loadImageWithURL:(NSURL *)URL target:(id)target action:(SEL)action;


Works the same as above, except the action will only be called if the loading is successful. Failure can still be detected using the AsyncImageLoadDidFail notification.

- (void)loadImageWithURL:(NSURL *)URL;


Works the same as above, but no target or actions are specified.Use AsyncImageLoadDidFinish and AsyncImageLoadDidFail to detect when the loading is complete.

- (void)cancelLoadingURL:(NSURL *)URL target:(id)target action:(SEL)action;


This cancels loading the image with the specified URL for the specified target and action.

- (void)cancelLoadingURL:(NSURL *)URL target:(id)target;


This cancels loading the image with the specified URL for any actions on the specified target;

- (void)cancelLoadingURL:(NSURL *)URL;


- (void)cancelLoadingImagesForTarget:(id)target action:(SEL)action;


This cancels loading all queued image URLs with the specified action on the specified target;

- (void)cancelLoadingImagesForTarget:(id)target;


- (NSURL *)URLForTarget:(id)target action:(SEL)action;


This returns the most recent image URL set for the given target and action, which may not be the next one to be loaded if several image URLs have been queued on that target.

- (NSURL *)URLForTarget:(id)target;


This returns the most recent image URL set for the given target, which may not be the next one to be loaded if several image URLs have been queued on that target.

## Usage（使用）

You can use the AsyncImageView class exactly as you would use a UIImageView. If you want to use it in Interface Builder, drag a regular UImageView or media image into your view as normal, then change its class to AsyncImageView in the inspector.

For cases where you cannot use an AsyncImageView, such as the embedded imageView of a UIButton or UITableView, the UIImageView category means that you can still set the imageURL property on the imageView to load the image in the background. You will not get the advanced features of the AsyncImageView class this way however (such as the loading spinner), unless you re-implement them yourself.

To load or download an image, simply set the imageURL property to the URL of the desired image. This can be a remote URL or a local fileURL that points to the application's bundle or documents folder.

If you want to display a placeholder image in the meantime, just manually set the image property of the UIImageView to your placeholder image and it will be overwritten once the image specified by the URL has loaded.

If you want to asynchronously load a smaller thumbnail image while the main image loads, just set the thumbnail URL first, then the full image URL. AsyncImageLoader will ensure that the images are loaded in the correct order. If the larger image is already cached, or loads first for some reason, the thumbnail image loading will be cancelled.

To detect when the image has finished loading, you can use NSNotificationCenter in conjunction with the AsyncImageLoadDidFinish notification, or you can use KVO (Key-Value Observation) to set up an observer on the UIImageView's image property. When the image has finished loading, the image will be set, and with KVO you can detect this and react accordingly.

By default, all loaded images are cached, and if the app loads a large number of images, the cache will keep building up until a memory warning is triggered. You can avoid memory warnings by manually removing items from the cache according to your own maintenance logic. You can also disable caching either universally or for specific images by setting the shared AsyncImageLoader's cache property to nil before loading an image (set it back to [AsyncImageLoader sharedInstance] to re-enable caching afterwards).

1. 该AsyncImageView不是基于GCD的,所以使用在UITableView或者UIButton中会出现一些使用上的限制

2. 可以加载图片序列,先加载小图再加载大图

3. 加载图片的时候可以显示出菊花

4. 图片成功加载后会有着渐隐出现的效果

5. 图片是否加载成功通过通知中心来实现

6. 比不上SDWebImage,但也有自己的亮点,还是挺好用的.

8 0
Qt使用MinGW编译,如何忽略警告
Qt使用MinGW编译,如何忽略警告
151 0
Android开发 - ImageView加载Base64编码的图片

1913 0

//设置可以获取imageView缓存 imageView.setDrawingCacheEnabled(true); //然后通过getDrawingCache方法获取BitMap Bitmap drawingCache = imageView.
1023 0
ImageView简单加载网络图片
private void loadImage() { mImageView = (ImageView) findViewById(R.id.imageView); try { URL url = new URL("http://images.
668 0
C#中手机号验证，邮箱验证

712 0
(翻译)火狐操作系统javascript API

829 0
Bitmap和ImageView显示下载的图片(I/O的理解)

867 0
.NET数据库编程求索之路--10.使用EF实现（划分输入验证层）
619 0
+关注