UIImage加載圖片的方式以及Images.xcassets對于加載方法的影響
2017.5.19更新:
- 更新了若干概念的理解
- 調整描述方式,行文更流暢
- 更新了代碼示例
- 調整文章結構,使其主題更精煉
創建圖片對象
根據是否緩存圖數據,有兩類創建UIImage
對象的方法可選:
Use the imageNamed:inBundle:compatibleWithTraitCollection: method (or the imageNamed: method) to create an image from an image asset or image file located in your app’s main bundle (or some other known bundle). Because these methods cache the image data automatically, they are especially recommended for images that you use frequently.
-
緩存:
imageNamed:
- 只需傳入
文件名.擴展名
即可。 - 可以加載bundle中
任意位置
的圖片,包括main bundle中其他bundle的。
- 只需傳入
-
imageNamed方法創建對象的步驟如下:
- 根據圖片文件名在緩存池中查找圖片數據,如存在,則創建對象并返回;
- 如果不存在,則從bundle中加載圖片數據,創建對象并返回;
- 如果相應的圖片數據不存在,返回nil。
Use the imageWithContentsOfFile: or initWithContentsOfFile: method to create an image object where the initial data is not in a bundle. These methods load the image data from disk each time, so you should not use them to load the same image repeatedly.
- 不緩存:
imageWithContentsOfFile:
- 必須傳入圖片文件的
全名(全路徑+文件名)
。 - 無法加載
Images.xcassets
中的圖片。
- 必須傳入圖片文件的
Images.xcassets
Images.xcassets
在app打包后,以Assets.car
文件的形式出現在bundle中。其作用在于:
自動識別@2x,@3x圖片,對內容相同但分辨率不同的圖片統一管理。
可以對圖片進行
Slicing
(即剪裁和拉伸)。其中的圖片資源只能通過UIimage的
imageNamed:
方法加載,通過NSBundle的pathForResource:ofType:
無法獲得圖片路徑。適合存放系統常用的,占用內存小的圖片資源。
只支持png / jpeg,不支持諸如gif等其他圖片格式;使用UIimage的
imageNamed:
加載時,只需提供文件名,不需提供擴展名。小心項目中的同名圖片,很有可能造成
異常和bug
。例如:兩個同名圖片,一個在Assets.xcassets中被sliced
,另一個沒有。則系統sliced
圖片。從其它項目拖拽圖片
時也要小心,如果這個圖片在上一個項目中sliced
過,如果連同相應的Contents.json
一起拷貝,則處理效果會被保留
。-
從別的的地方加載圖片,必須在文件名后加擴展名,例如:
// pic.jpg處于根目錄下 [UIImage imageNamed:@"pic"]; // 錯誤,圖片未能正確加載 [UIImage imageNamed:@"pic.jpg"]; // 正確
從其他Bundle中加載資源
-
從main bundle中其他bundle加載資源,可以分為四步:
- 在main bundle中找到特定bundle。
- 載入bundle,即創建bundle對象。
- 從bundle中獲取資源路徑。注意,如果資源位于次級目錄,則必須指明路徑。
- 通過路徑創建對象。
例如,如下代碼從app bundle根目錄下的另一個bundle中獲取一張圖片。
- (void)viewDidLoad {
[super viewDidLoad];
// 1. 在main bundle中找到特定bundle
NSString *sampleBundlePath = [[NSBundle mainBundle] pathForResource:@"SampleBundle.bundle" ofType:nil];
// 2. 載入bundle,即創建bundle對象
NSBundle *sampleBundle = [NSBundle bundleWithPath:sampleBundlePath];
// 3. 從bundle中獲取資源路徑
// 注意這里的圖片位于通用資源目錄下的Images二級目錄,相對路徑要明確這種關系
NSString *pic1Path = [sampleBundle pathForResource:@"pic1.png" ofType:nil];
// 4. 通過路徑創建對象
UIImage *image = [UIImage imageWithContentsOfFile:pic1Path];
}
如下代碼從app bundle根目錄下的另一個bundle中獲取一張圖片
- 更多關于bundle的信息,可以參考筆記@Bundle Programming Guide。