iOS 图片命名规则

Updating Your Image Resource Files

Apps running in iOS 4 should now include two separate files for each image resource. One file provides a standard-resolution version of a given image, and the second provides a high-resolution version of the same image. The naming conventions for each pair of image files is as follows:

Standard: <ImageName> <device_modifier>.<filename_extension>
High resolution: <ImageName>@2x<device_modifier>.<filename_extension>

The <ImageName> and <filename_extension> portions of each name specify the usual name and extension for the file. The <device_modifier> portion is optional and contains either the string ~ipad
or ~iphone. You include one of these modifiers when you want to specify different versions of an image for iPad and iPhone. The inclusion of the @2x
modifier for the high-resolution image is new and lets the system know that the image is the high-resolution variant of the standard image.
Important: The order of the modifiers is critical. If you incorrectly put the @2x after the device modifier, iOS will not find the image.

When creating high-resolution versions of your images, place the new versions in the same location in your app bundle as the original.

上面是引自苹果官方文档的一段话,详细介绍了如何命名图片文件。
eg:
image1@2x~ipad.png ,image1@3x~iphone.png
在代码中,如果要使用这张图片,应该
UIImage *image = [UIImage imageNamed:@"image1.png"];

NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
NSString *path = [resourcePath stringByAppendingPathComponent:@"image1.png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];

此时系统会自动根据设备的分辨率及类型,自动选择正确的图片。
错误的写法:
[UIImage imageNamed:@"image1@2x.png"],[UIImage imageNamed:@"image1@2x~ipad.png"]

NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
NSString *path = [resourcePath stringByAppendingPathComponent:@"image1@2x~ipad.png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];

错误的写法虽然也可以拿到图片,但是并不会根据iPhone和ipad自动切换,2倍图3倍图也不会自动切换。

如果使用如下的写法,则文件名必须写全。

NSString *path = [[NSBundle mainBundle] pathForResource:@"image1@2x~ipad" ofType:@"png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];

这是因为- (nullable NSString *)pathForResource:(nullable NSString *)name ofType:(nullable NSString *)ext;方法只是查找对应的资源文件,并不会自动补全,所以如果不写全文件名,则查找不到对应的文件,会返回nil。也即path = nil,所以如果不写全是不能得到对应的image

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,552评论 5 6
  • 在农民感叹种地亏本,个体户唠叨生意不好做的今天,小城公交车也迎來艰难的日子。。。。。。空调开的挺凉,一个司机,一名...
    日光浴的男子阅读 160评论 0 0
  • 曾经被告知:阅读能暂时屏蔽掉呱噪浮夸的世俗 因身心合一的专注 而沉醉 安享知识 文化的熏陶 ... 哎......
    璐狗尔阅读 160评论 1 0
  • 3420-3430 区域 今天 早盘的走势 就告诉了我们 这个位置是由支撑的 那么今后我们要记住这个区域 可以拿纸...
    烟花扬州阅读 484评论 0 49
  • 分包中甘今天一把手过来,因为那边营区似乎也没有足够的房间,加上本身营区也比较简陋,和我们的营区没法比,所以就商量着...
    绪红阅读 252评论 0 0