美文网首页
iOS 图片命名规则

iOS 图片命名规则

作者: whlpkk | 来源:发表于2017-05-11 10:54 被阅读268次

    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

    相关文章

      网友评论

          本文标题:iOS 图片命名规则

          本文链接:https://www.haomeiwen.com/subject/syxotxtx.html