iOS备忘录实用小功能IOS技术收录

UIImage加载图片的方式以及Images.xcassets对

2015-10-19  本文已影响18840人  fever105

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.

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.

Images.xcassets

Images.xcassets在app打包后,以Assets.car文件的形式出现在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中获取一张图片
上一篇下一篇

猜你喜欢

热点阅读