iOS學習 --- 製作並調用Bundle資源包

背景:

在開發項目中,我們公司的產品要給別人用,除了把代碼封裝成靜態庫之外,還需要把你的圖片等資源封裝成bundle包。 這樣,別人拿你的產品來用的時候,既不會看到你的代碼,也看不到你的圖片等資源。如果他想要用你的圖片資源,那麼前提是他要知道你bundle裏面的圖片資源的名稱。

什麼是Bundle文件?

簡單理解,就是資源文件包。我們將許多圖片、XIB、文本文件組織在一起,打包成一個Bundle文件。方便在其他項目中引用包內的資源。

Bundle文件的特點?

Bundle是靜態的,也就是說,我們包含到包中的資源文件作爲一個資源包是不參加項目編譯的。也就意味着,bundle包中不能包含可執行的文件。它僅僅是作爲資源,被解析成爲特定的2進制數據。

製作步驟:

一,創建bundle項目

打開Xcode

command + shift +N

新建項目

bundle項目屬於mac開發裏面的種類,所以選擇mac下面的。

圖1-1圖1-1

 

圖1-2

二,在bundle資源包中添加圖片

方法1:

1>使用Asset管理圖片

因爲Xcode的Assets,可以自動識別圖片的二倍圖還是三倍圖,所以,就在bundle工程裏面創建一個Assets,到時候就調用圖片名稱,會自動對應加載;

反正,只要把後綴爲@2x,@3x的圖片拖到Assets就會自動放到對應的位置;

下面就創建一個Assets文件

圖2-1

2>拖入對應的圖片

圖2-2

 

方法2:創建images文件夾,如圖所示,再拖入對應後綴名的圖片;

 

 

三,command + B編譯生成Bundle包

Command + B後生成Bundle包,點擊Products裏面的bundle文件,Show in Finder 看到製作好的Bundle包

圖3-1

 

完成,下面就是在工程中使用了......

四,集成到需要圖片資源的項目中使用

把Bundle資源包放到項目的任意(或指定)的文件夾下,如下圖:

圖4-1

 

調用:


UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];    
button.frame = CGRectMake(100, 200, 30, 30);    
[self.view addSubview:button];

//設置圖片
//方法1

NSString *bundlePath = [[ NSBundle mainBundle] pathForResource:@"M_Images" ofType :@"bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
NSString *img_path = [bundle pathForResource:[NSString stringWithFormat:@"%@",@"close"] ofType:@"png"];
UIImage*image_1=[UIImage imageWithContentsOfFile:img_path];
[button setImage:image_1 forState:UIControlStateNormal];


//方法2
if (@available(iOS 8.0, *)) {
        [button setImage:[UIImage imageNamed:@"close" inBundle:ZFBundle compatibleWithTraitCollection:nil] forState:UIControlStateNormal];
    } else {
        // Fallback on earlier versions
    }


//上面用到了宏定義

#define ZFBundle_Name @"M_Images.bundle"
#define ZFBundle_Path [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:ZFBundle_Name]
#define ZFBundle [NSBundle bundleWithPath:ZFBundle_Path]

 

總結:

以上就是今天的學習內容,請多指正,謝謝!!!

參考:

https://blog.csdn.net/Feng512275/article/details/77982962

https://blog.csdn.net/u012265444/article/details/79138958

https://blog.csdn.net/yuge486/article/details/79580339

https://www.jianshu.com/p/44aacd5b8adb

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章