(IOS)根據bundle中的檔名讀取圖片

weixin_33907511發表於2018-07-31

+ (UIImage*)imageWithFileName:(NSString*)name {

    NSString*extension =@"png";


    NSArray*components = [namecomponentsSeparatedByString:@"."];

    if([componentscount] >=2) {

        NSUIntegerlastIndex = components.count-1;

        extension = [componentsobjectAtIndex:lastIndex];


        name = [namesubstringToIndex:(name.length-(extension.length+1))];

    }


    // 如果為Retina螢幕且存在對應圖片,則返回Retina圖片,否則查詢普通圖片

    if([UIScreenmainScreen].scale==2.0) {

        name = [namestringByAppendingString:@"@2x"];


        NSString*path = [[NSBundlemainBundle]pathForResource:nameofType:extension];

        if(path !=nil) {

            return [UIImage imageWithContentsOfFile:path];

        }

    }


    if([UIScreenmainScreen].scale==3.0) {

        name = [namestringByAppendingString:@"@3x"];


        NSString*path = [[NSBundlemainBundle]pathForResource:nameofType:extension];

        if(path !=nil) {

            return [UIImage imageWithContentsOfFile:path];

        }

    }


    NSString*path = [[NSBundlemainBundle]pathForResource:nameofType:extension];

    if(path) {

        return [UIImage imageWithContentsOfFile:path];

    }


    return nil;

}

相關文章