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

时间:2018-06-17 21:15:30

标签: ios iphone filesystems image-scaling

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

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 个答案:

答案 0 :(得分:0)

1)在finder中创建文件夹结构,图像名称相同 finder directory structure

2)拖动根文件夹(图像)添加到项目中创建文件夹引用
add files alert
final project structure

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