【问题标题】:Converting imageNamed to imageWithContentsOfFile:将 imageNamed 转换为 imageWithContentsOfFile:
【发布时间】:2014-03-16 08:41:00
【问题描述】:

我的图片代码是

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

这缓存了太多内存,我在上一个问题中被告知要交换我的代码以使用

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

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

编写代码的正确方法是什么?我是否将该代码按原样放在我的 .m 中?

【问题讨论】:

    标签: ios animation memory


    【解决方案1】:

    首先你应该检查是否使用视网膜图片:

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

    如果您使用的是视网膜图片,请在图片名称中添加@2x,如下所示:

    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】:

      由于您的 GetImgWithoutCaching 函数返回您需要的 UIImage:

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

      【讨论】:

      • 您必须将函数 GetImgWithoutCaching() 添加到您的 .m 文件中!
      猜你喜欢
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多