iOS 根据内容比例加载不同的图像

iOS load different image based on content scale

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

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

1) 在 finder 中创建您的文件夹结构,使用相同的图像名称


2) 将根文件夹 (Images) 拖到项目中 Create folder references



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")