Issue with loading and caching retina images for U

2019-08-25 20:24发布

问题:

What I have

For my game I'm creating several animations using view.animationImages = imagesArray; [view startAnimating];

In my animation helper class I use this

- (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];
    else
        return [UIImage imageWithContentsOfFile:path];
}

- (NSMutableArray *)generateCachedImageArrayWithFilename:(NSString *)filename extension:(NSString *)extension andImageCount:(int)count
{
    _imagesArray = [[NSMutableArray alloc] init];
    _fileExtension = extension;
    _imageName = filename;
    _imageCount = count;

    for (int i = 0; i < count; i++)
    {
        NSString *tempImageNames = [NSString stringWithFormat:@"%@%i", filename, i];
        NSString *imagePath = [[NSBundle mainBundle] pathForResource:tempImageNames ofType:extension];

        UIImage *frameImage = [self loadRetinaImageIfAvailable:imagePath];
        UIGraphicsBeginImageContext(frameImage.size);
        CGRect rect = CGRectMake(0, 0, frameImage.size.width, frameImage.size.height);
        [frameImage drawInRect:rect];
        UIImage *renderedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        [_imagesArray addObject:renderedImage];

        if (_isDoublingFrames)
        {
            [_imagesArray addObject:renderedImage];
        }
        else if (_isTriplingFrames)
        {
            [_imagesArray addObject:renderedImage];
            [_imagesArray addObject:renderedImage];
        }

        NSLog(@"filename = %@", filename);
    }

    return _imagesArray;
}

Problem and facts

  • Without caching images I got retina versions of images byt my animations are not fluent
  • If I cache images this way, animations are ok, but uses non-retina versions of images

Please is there some other way to cache and get retina versions?

回答1:

Are these images located in your application bundle? If so this logic is all unnecessary because the imageWithContentsOfFile: method will already detect and load the @2x image on a retina device.

Also, you'd be better off using the [UIImage imageNamed:] method instead because this automatically caches the image for re-use, and decompresses it immediately, avoiding the need for manually caching the images, or for that trickery with drawing it into an offscreen CGContext.