• 无法正确加载@2x的解决办法

    为使用retina显示,我们一般把图片的高分辨率版本存为@2x的形式,但是iOS 4.1以前的版本,如果使用imageWithContentsOfFile是无法保证@2x文件正确加载的。我使用如下方法解决此问题:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    // UIImage+Extras.h
    @interface UIImage (Extras)

    - (id)initWithContentsOfResolutionIndependentFile:(NSString *)path;
    + (UIImage*)imageWithContentsOfResolutionIndependentFile:(NSString *)path;

    @end

    // UIImage+Extras.m
    - (id)initWithContentsOfResolutionIndependentFile:(NSString *)path {
        if ( [[[UIDevice currentDevice] systemVersion] intValue] >= 4 && [[UIScreen mainScreen] scale] == 2.0 ) {
            NSString *path2x = [[path stringByDeletingLastPathComponent]
                                stringByAppendingPathComponent:[NSString stringWithFormat:@"%@@2x.%@",
                                                                [[path lastPathComponent] stringByDeletingPathExtension],
                                                                [path pathExtension]]];
           
            if ( [[NSFileManager defaultManager] fileExistsAtPath:path2x] ) {
                return [self initWithCGImage:[[UIImage imageWithData:[NSData dataWithContentsOfFile:path2x]] CGImage] scale:2.0 orientation:UIImageOrientationUp];
            }
        }
       
        return [self initWithData:[NSData dataWithContentsOfFile:path]];
    }

    + (UIImage*)imageWithContentsOfResolutionIndependentFile:(NSString *)path {
        return [[[UIImage alloc] initWithContentsOfResolutionIndependentFile:path] autorelease];
    }
     
  • 怎样从core graphics获取UIImage

    从core graphics获取UIImage的方法:

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    - (void)viewDidLoad
    {
        [super viewDidLoad];

        UIGraphicsBeginImageContext(CGSizeMake(20,20));
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextBeginPath(ctx);
        CGContextAddArc(ctx, 10, 10, 10, 0, 2*M_PI, 1);
        CGContextSetRGBFillColor(ctx, 1,0, 0, 1);
        CGContextFillPath(ctx);
        UIImage *redBall = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        UIImageView *redBallView = [[UIImageView alloc] initWithImage:redBall];
        redBallView.center = CGPointMake(160,330);
        [self.view addSubview:redBallView];
    }