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:[email protected]~ipad.png
,[email protected]~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:@"[email protected]"]
,[UIImage imageNamed:@"[email protected]~ipad.png"]
NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
NSString *path = [resourcePath stringByAppendingPathComponent:@"[email protected]~ipad.png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];
错误的写法虽然也可以拿到图片,但是并不会根据iPhone和ipad自动切换,2倍图3倍图也不会自动切换。
如果使用如下的写法,则文件名必须写全。
NSString *path = [[NSBundle mainBundle] pathForResource:@"[email protected]~ipad" ofType:@"png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];
这是因为- (nullable NSString *)pathForResource:(nullable NSString *)name ofType:(nullable NSString *)ext;
方法只是查找对应的资源文件,并不会自动补全,所以如果不写全文件名,则查找不到对应的文件,会返回nil
。也即path = nil
,所以如果不写全是不能得到对应的image
。
上一篇: golang 打印函数名/文件名/行号
下一篇: c接口跨平台头文件模板