Converting imageNamed to imageWithContentsOfFile:

本小妞迷上赌 提交于 2020-01-06 14:44:10

问题


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];
}


来源:https://stackoverflow.com/questions/21822520/converting-imagenamed-to-imagewithcontentsoffile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!