在ios开发中,使用图片的方式有两种一种方式可以将图片散落在工程中,一种方式可以用bundle统一管理。
文件形式
路径读取
我们可以将图片散落在工程中,如图所示:
如果用这种形式,可以使用一下代码进行获取
UIImage *img1 = [UIImage imageNamed:@"umeng_share_solid_icon"];
UIImage *img2 = [UIImage imageNamed:@"umeng_app_icon"];
你也可以建立一个文件夹,将图片放入对应的文件夹中:
bundle读取
我们可以把整个工程看做是一个bundle,也就是mainBundle,这样可以使用如下方法读取:
NSBundle *mainBundle = [NSBundle mainBundle];
// 用对象mainBundle获取图片路径
NSString *imagePath = [mainBundle pathForResource:imgName ofType:@"png"];
return [[UIImage alloc] initWithContentsOfFile:imagePath];
自定义bundle
在工程目录下新建一个文件夹,改名为xxx.bundle,一定要以.bundle为后缀。
以后打开此文件夹,要鼠标右键-显示包内容,直接双击不行。
获取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中的图片能不能以路径的形式获取呢?当然可以
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];