※変なタイトルでスミマセン
UIImageViewのカスタムなカテゴリメソッドを呼ぶだけで自動的にキャッシュが作られる。
// Setting a remote image [imageView hnk_setImageFromURL:url]; // Setting a local image [imageView hnk_setImageFromFile:path]; // Setting an image manually. Requires you to provide a key. [imageView hnk_setImage:image withKey:key];リモートからの画像取得も裏でやってくれる。
lightweightとうたってはいるがそれは使い勝手のことで内部はそれなりに高機能。
キャッシュはメモリ(NSCache)→ディスクの順でLRU。
作成するキャッシュイメージのフォーマットのカスタマイズも可能。
HNKCacheFormat *format = [HNKCache sharedCache].formats[@"thumbnail"];
if (!format)
{
format = [[HNKCacheFormat alloc] initWithName:@"thumbnail"];
format.size = CGSizeMake(320, 240);
format.scaleMode = HNKScaleModeAspectFill;
format.compressionQuality = 0.5;
format.diskCapacity = 1 * 1024 * 1024; // 1MB
format.preloadPolicy = HNKPreloadPolicyLastSession;
}
imageView.hnk_cacheFormat = format;付属のサンプルでは UICollectionViewにリモートからの画像を実行時に読み込んで表示している。
セルのコードはたったこれだけ(主要部分だけ抜粋)。
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
HNKDemoCollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
NSString *urlString = _items[indexPath.row];
NSURL *url = [NSURL URLWithString:urlString];
[cell.imageView hnk_setImageFromURL:url];
return cell;
}
画像の非同期なダウンロードや終了後の再描画など全部やってくれる。これは簡単。キャッシュ時リサイズ後のポスト処理も定義できる。
format.postResizeBlock = ^UIImage* (NSString *key, UIImage *image) {
NSString *title = [key.lastPathComponent stringByDeletingPathExtension];
title = [title stringByReplacingOccurrencesOfString:@"sample" withString:@""];
UIImage *modifiedImage = [image demo_imageByDrawingColoredText:title];
return modifiedImage;
};デモでは画像に文字を重ねている。※HNK_USE_CUSTOM_FORMATを1にすると動作確認できる。他にもディスク制限やプレースホルダ画像を表示するなど痒いところに届く感じでよくできてる。
iOS7以降で利用可能。内部ではNSURLSessionを使っていた。