差分早見表
Method | Cache | Speed | @2x | Extention | Thread-Safe | Load Asset Catalog | Localize |
---|---|---|---|---|---|---|---|
imageNamed | YES | Fast | Auto | Unnecessary | NO | ImageSetName | User's Preferences |
imageWithContentsOfFile | NO | Slow | Auto | Necessary | YES | Not supported | Not supported |
- PNG以外のフォーマットでは拡張子の省略はできない
- storyboard上で設定したimageView.imageもキャッシュされる
- imageWithContentsOfFileの@2x判定は iOS4.0ではバグがあったが4.1で直った
- imageNamedは当初メインバンドルを探し見つからなければユーザー設定言語のlproj内を自動で探す
- imageWithContentsOfFileでもpathForResourceで作ったパスならユーザー設定のローカライズファイルを探す
imageWithContentsOfFileで@2xの画像が取得出来ない場合
pathForResourceは@2x画像しかバンドルに無い時に@2xを省略してしまうとnilを返す、
imageWithContentsOfFileの引数に使う場合注意がいる。
// @2xしかないとnilを返す
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"png"];
// imageはnilになる
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
対策は..
- @1xのfileName.pngも用意する
- 拡張子を省略せず
@"fileName@2x"
とする - 以下のように明示的に画像までのパス文字列を引数に渡す
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *imagePath = [bundlePath stringByAppendingPathComponent:@"fileName.png"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
参考
AssetCatalogの良い点やハマリ点
http://aqubiblog.blogspot.jp/2014_02_01_archive.html
UIImage imageNamed: ってスレッドセーフ?
http://togetter.com/li/104905
iOSにおける描画と印刷のガイド
https://developer.apple.com/jp/devcenter/ios/library/documentation/DrawingPrintingiOS.pdf