【IOS初學者】bundle知識點總結

在ios開發中,使用圖片的方式有兩種一種方式能夠將圖片散落在工程中,一種方式能夠用bundle統一管理。javascript

文件形式

路徑讀取

咱們能夠將圖片散落在工程中,如圖所示:java

若是用這種形式,能夠使用一下代碼進行獲取ios

UIImage *img1 = [UIImage imageNamed:@"umeng_share_solid_icon"];
    UIImage *img2 = [UIImage imageNamed:@"umeng_app_icon"];複製代碼

你也能夠創建一個文件夾,將圖片放入對應的文件夾中:app

bundle讀取

咱們能夠把整個工程看作是一個bundle,也就是mainBundle,這樣能夠使用以下方法讀取:spa

NSBundle *mainBundle = [NSBundle mainBundle];
    // 用對象mainBundle獲取圖片路徑
    NSString *imagePath = [mainBundle pathForResource:imgName ofType:@"png"];
  return  [[UIImage alloc] initWithContentsOfFile:imagePath];複製代碼

自定義bundle

在工程目錄下新建一個文件夾,更名爲xxx.bundle,必定要以.bundle爲後綴。
之後打開此文件夾,要鼠標右鍵-顯示包內容,直接雙擊不行。code

獲取bundle中的圖片

NSString *bundlePath = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"image.bundle"];
    NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
    NSString *img_path = [bundle pathForResource:imgName ofType:@"png"];
 [UIImage imageWithContentsOfFile:img_path];複製代碼

獲取bundle中的txt

NSString *bundlePath = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"image.bundle"];
    NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
    NSString *txtPath = [bundle pathForResource:name ofType:@"txt"];
    return [[NSString  alloc] initWithContentsOfFile:txtPath encoding:NSUTF8StringEncoding error:nil];複製代碼

文件形式讀取

那麼自定義bundle中的圖片能不能以路徑的形式獲取呢?固然能夠cdn

UIImage *img3 = [UIImage imageNamed:@"image.bundle/umeng_share_solid_icon"];
 UIImage *img4 = [UIImage imageNamed:@"image.bundle/umeng_app_icon"];複製代碼

經過mainBundle獲取

上面提到過能夠把整個工程的group看作是mainBundle
那麼也就能夠這樣讀取了對象

NSString *file2 = [[NSBundle mainBundle] pathForResource:@"image.bundle/xxx" ofType:@"png"];
UIImage *img2 = [UIImage imageWithContentsOfFile:file2];複製代碼
相關文章
相關標籤/搜索