How to get [UIImage imageWithContentsOfFile:] and High Res Images working

前端 未结 6 1189
星月不相逢
星月不相逢 2020-12-24 08:57

As many people are complaining it seems that in the Apple SDK for the Retina Display there\'s a bug and imageWithContentsOfFile actually does not automatically load the 2x i

6条回答
  •  孤独总比滥情好
    2020-12-24 09:38

    [UIImage imageWithContentsOfFile:] doesn't load @2x graphics if you specify an absolute path.

    Here is a solution:

    - (UIImage *)loadRetinaImageIfAvailable:(NSString *)path {
    
        NSString *retinaPath = [[path stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@@2x.%@", [[path lastPathComponent] stringByDeletingPathExtension], [path pathExtension]]];
    
        if( [UIScreen mainScreen].scale == 2.0 && [[NSFileManager defaultManager] fileExistsAtPath:retinaPath] == YES) 
            return [[[UIImage alloc] initWithCGImage:[[UIImage imageWithData:[NSData dataWithContentsOfFile:retinaPath]] CGImage] scale:2.0 orientation:UIImageOrientationUp] autorelease];
        else
            return [UIImage imageWithContentsOfFile:path];
    }
    

    Credit goes to Christof Dorner for his simple solution (which I modified and pasted here).

提交回复
热议问题