Converting imageNamed to imageWithContentsOfFile:

2019-08-30 19:58发布

问题:

My code for my images is

-(IBAction)start:(id)sender
{
    animation.animationImages = [NSArray arrayWithObjects:
                                 [UIImage imageNamed:@"Paddle 1.png"],
                                 [UIImage imageNamed:@"Paddle 2.png"],
                                 [UIImage imageNamed:@"Paddle 3.png"],
                                 [UIImage imageNamed:@"Paddle 4.png"],
nil];
    [animation setAnimationRepeatCount:0];
    animation.animationDuration = 2.5;
    [animation startAnimating];
}

This is caching too much memory and I was told in a previous question to swap my code to using

[UIImage imageWithContentsOfFile: GetImgWithoutCaching(@"Paddle 1.jpg")]

and

UIImage* GetImgWithoutCaching(NSString* imgName)
{
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:imgName ofType:nil];
    return [UIImage imageWithContentsOfFile:imagePath];
}

What is the correct way of writing the code? do i place that code in my .m as is?

回答1:

First you should check if using retina picture:

BOOL isHighResolution = NO;
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    if ([UIScreen mainScreen].scale > 1) {
        isHighResolution = YES;
    }
}

if you are using retina picture, add @2x to image name, like this:

NSString *noExtFileName = [name stringByDeletingPathExtension];
if (isHighResolution) {
    if (![noExtFileName hasSuffix:@"@2x"]) {
       noExtFileName = [noExtFileName stringByAppendingString:@"@2x"];
    }
}

 //if image only "png" type
return [[NSBundle mainBundle] pathForResource:noExtFileName ofType:@"png"];


回答2:

Since your GetImgWithoutCaching function returns a UIImage you would need:

-(IBAction)start:(id)sender
{
    animation.animationImages = [NSArray arrayWithObjects:
                                 GetImgWithoutCaching(@"Paddle 1.jpg"),
                                 GetImgWithoutCaching(@"Paddle 2.jpg"),
                                 GetImgWithoutCaching(@"Paddle 3.jpg"),
                                 GetImgWithoutCaching(@"Paddle 4.jpg"),
nil];
    [animation setAnimationRepeatCount:0];
    animation.animationDuration = 2.5;
    [animation startAnimating];
}