Search code examples
iosiphonefilesystemsimage-scaling

iOS load different image based on content scale


So I am trying to change the directory in which to load an image from based upon what content scale I should be at but I cannot figure out how to load the same image name from different directories.

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

My file structure looks like this:file structure


Solution

  • 1) Create your folder structure in finder, with same image names
    finder directory structure

    2) Drag root folder (Images) add to project as Create folder references
    add files alert
    final project structure

    3) Use following extension or modify yourself as your needs

    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) Use it like

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