UIImage加載圖片的方式以及Images.xcassets對于加載方法的影響

UIImage加載圖片的方式以及Images.xcassets對于加載方法的影響

2017.5.19更新:

  1. 更新了若干概念的理解
  2. 調整描述方式,行文更流暢
  3. 更新了代碼示例
  4. 調整文章結構,使其主題更精煉

創建圖片對象

根據是否緩存圖數據,有兩類創建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方法創建對象的步驟如下:

    1. 根據圖片文件名在緩存池中查找圖片數據,如存在,則創建對象并返回;
    2. 如果不存在,則從bundle中加載圖片數據,創建對象并返回;
    3. 如果相應的圖片數據不存在,返回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加載資源,可以分為四步:

    1. 在main bundle中找到特定bundle。
    2. 載入bundle,即創建bundle對象。
    3. 從bundle中獲取資源路徑。注意,如果資源位于次級目錄,則必須指明路徑。
    4. 通過路徑創建對象。
  • 例如,如下代碼從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中獲取一張圖片
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容