【问题标题】:iOS load different image based on content scaleiOS根据内容比例加载不同的图像
【发布时间】:2018-11-26 18:31:15
【问题描述】:

所以我试图根据我应该采用的内容比例更改加载图像的目录,但我不知道如何从不同的目录加载相同的图像名称。

int m_contentScale = [GameController getContentScale];
NSLog(@"%i", m_contentScale);
NSString* contentScalePath;
NSString* combinedPath;
CGImageRef imageReference;
do{
    switch (m_contentScale) {
        case 1:
            contentScalePath = @"Rush Racing/Resources/Images/SD/";
            break;
        case 2:
            contentScalePath = @"Rush Racing/Resources/Images/HD/";
            break;
        case 3:
            contentScalePath = @"/Rush Racing/Resources/Images/XHD/";
            break;
        case 4:
            contentScalePath = @"Rush Racing/Resources/Images/XXHD/";
            break;

        default:
            contentScalePath = @"Rush Racing/Resources/Images/SD/";
            break;
    }
    combinedPath = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], contentScalePath, path];
    NSLog(@"%@", combinedPath);
    imageReference = [[UIImage imageWithContentsOfFile:combinedPath] CGImage];

    //if it gets to the SD folder and still cant find a suitable graphic it will search globally for the graphic.
    if((m_contentScale == 1) && (imageReference == nil)){
        imageReference = [[UIImage imageNamed:path] CGImage];
        if(!imageReference) break;
    }
    if(m_contentScale > 1) m_contentScale--;//reduce content scale so it will go through all the folders
    //smaller than it until it finds the graphic it is looking for.
}while(imageReference == nil);

我的文件结构如下:file structure

【问题讨论】:

    标签: ios iphone filesystems image-scaling


    【解决方案1】:

    1) 在查找器中创建具有相同图像名称的文件夹结构


    2)拖动根文件夹(图像)添加到项目作为创建文件夹引用



    3)使用以下扩展或根据需要修改自己

    extension UIImage {
        convenience init?(named: String, contentScale: String) {
            guard let path = Bundle.main.resourcePath else { return nil }
            let fileUrl = URL(fileURLWithPath: path)
                .appendingPathComponent("Images")
                .appendingPathComponent(contentScale)
                .appendingPathComponent(named)
            guard let data = try? Data(contentsOf: fileUrl) else { return nil }
            self.init(data: data)
        }
    }
    

    3) 像这样使用它

    let img = UIImage(named: "Blue-Speaker.png", contentScale: "HD")
    let img2 = UIImage(named: "Blue-Speaker.png", contentScale: "SD")
    

    【讨论】:

      猜你喜欢
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      相关资源
      最近更新 更多