• iOS生成Bundle包及使用


    什么是Bundle文件?

    简单理解,就是资源文件包。我们将许多图片、XIB、文本文件组织在一起,打包成一个Bundle文件。方便在其他项目中引用包内的资源。

    Bundle文件的特点?

    Bundle是静态的,也就是说,我们包含到包中的资源文件作为一个资源包是不参加项目编译的。也就意味着,bundle包中不能包含可执行的文件。它仅仅是作为资源,被解析成为特定的2进制数据。

    制作Bundle

    1.新建bundle项目(xcode-file-new-project)

    2.添加需要的图片

    加入你需要编译在bundle中的资源文件。

    3.你可以对编译的bundle进行一些可选的设置(可选)

    a.作为资源包,仅仅需要编译就好,无需安装相关的配置

     

    b.同样要删除安装路径。

     

    c.iOS系统

    d.进行以下设置否则Bundle里的图片为tiff格式

     

     编译生成 Bundle 文件。---分别选择 Generic iOS Device 和任意一个模拟器各编译一次,编译完后,我们会看到工程中 Products 文件夹下的 SourcesBundle.bundle 由红色变成了黑色。

    show in finder,看看生成的文件。我们看到它为真机和模拟器都生成了 .bundle 资源文件

    项目集成bundle

    将编译好的MyBundle.bundle 文件直接加入到需要的项目中。

    使用bundle中的资源

    需要注意的就是,bundle是静态的,不进行编译的资源文件。所以,要使用bundle中的资源,就需要找到相应的资源路径。

    VC获得bundle中的资源

    NSString * bundlePath = [[NSBundle mainBundle]pathForResource: @"MyBundle"ofType:@"bundle"];

    NSBundle *resourceBundle =[NSBundle bundleWithPath:bundlePath];

    UIViewController *vc =[[UIViewController alloc]initWithNibName:@"vc_name"bundle:resourceBundle];

    图片获得bundle中的资源

    UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(50,50,50,50)];

    UIImage *image = [UIImage

    imageNamed:@"MyBundle.bundle/woquanbaobao"];

    [imgView setImage:image];

    或者

    UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(50,50,50,50)];

    NSString *imgPath= [bundlePath stringByAppendingPathComponent:@"woquanbaobao.png"];

    UIImage *image_1=[UIImage imageWithContentsOfFile:imgPath];

    [imgView setImage:image_1];

    当然,可以写成预编译语句:

    #define MYBUNDLE_NAME @"MyBundle.bundle"

    #define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent: MYBUNDLE_NAME]

    #define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]



    效果图



  • 相关阅读:
    Linux下安装SVN服务端小白教程
    在 Linux 下搭建 Git 服务器
    Linux系统中安装软件的几种方式
    springboot系列(十)springboot整合shiro实现登录认证
    shiro系列五、shiro密码MD5加密
    springboot系列(九)springboot使用druid数据源
    springboot系列(七) 项目热加载
    访问网页出现DNS错误
    SpringBoot入门
    MyBatisCodeHelper-Pro插件破解版[2.8.2] 【拒绝度盘】
  • 原文地址:https://www.cnblogs.com/huangzs/p/8037642.html
Copyright © 2020-2023  润新知