UIImage加载图片的方式以及Images.xcassets对于加载方法的影响

 

创建图片对象

根据是否缓存图数据,有两类创建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.

  • 缓存:imageNamed:

    • 只需传入文件名.扩展名即可。
    • 可以加载bundle中任意位置的图片,包括main bundle中其他bundle的。
  • imageNamed方法创建对象的步骤如下:

    1. 根据图片文件名在缓存池中查找图片数据,如存在,则创建对象并返回;
    2. 如果不存在,则从bundle中加载图片数据,创建对象并返回;
    3. 如果相应的图片数据不存在,返回nil。
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.
  • 不缓存:imageWithContentsOfFile:
    • 必须传入图片文件的全名(全路径+文件名)
    • 无法加载Images.xcassets中的图片。

Images.xcassets

Images.xcassets在app打包后,以Assets.car文件的形式出现在bundle中。其作用在于:

  • 自动识别@2x,@3x图片,对内容相同但分辨率不同的图片统一管理。

  • 可以对图片进行Slicing(即剪裁和拉伸)。

  • 其中的图片资源只能通过UIimage的imageNamed:方法加载,通过NSBundle的pathForResource:ofType:无法获得图片路径。

  • 适合存放系统常用的,占用内存小的图片资源。

  • 只支持png / jpeg,不支持诸如gif等其他图片格式;使用UIimage的imageNamed:加载时,只需提供文件名,不需提供扩展名。

  • 小心项目中的同名图片,很有可能造成异常和bug。例如:两个同名图片,一个在Assets.xcassets中被sliced,另一个没有。则系统sliced图片。

  • 从其它项目拖拽图片时也要小心,如果这个图片在上一个项目中sliced过,如果连同相应的Contents.json一起拷贝,则处理效果会被保留

  • 从别的的地方加载图片,必须在文件名后加扩展名,例如:

    // pic.jpg处于根目录下
    [UIImage imageNamed:@"pic"]; // 错误,图片未能正确加载
    [UIImage imageNamed:@"pic.jpg"]; // 正确
    

从其他Bundle中加载资源

  • 从main bundle中其他bundle加载资源,可以分为四步:

    1. 在main bundle中找到特定bundle。
    2. 载入bundle,即创建bundle对象。
    3. 从bundle中获取资源路径。注意,如果资源位于次级目录,则必须指明路径。
    4. 通过路径创建对象。
  • 例如,如下代码从app 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];
    
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值