LoginSignup
27
26

More than 5 years have passed since last update.

imageNamedとimageWithContentsOfFileの差分メモ

Last updated at Posted at 2014-07-31

差分早見表

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

NSBundleクラスリファレンス
https://developer.apple.com/library/Mac/documentation/Cocoa/Reference/Foundation/Classes/NSBundle_Class/Reference/Reference.html#//apple_ref/occ/clm/NSBundle/pathForResource:ofType:inDirectory:

27
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
26