【问题标题】:imageWithContentsOfFile vs imageNamed (imageWithContentsOfFile return a low quality image )imageWithContentsOfFile 与 imageNamed(imageWithContentsOfFile 返回低质量图像)
【发布时间】:2013-03-31 07:17:46
【问题描述】:

有一次,我把我所有的图片都放在了 APP Bundle 中。我使用 imageNamed 函数来获取图像。后来,我决定在应用启动时将一些图片复制到 Document 中。所以,我不能再使用 imageNamed 函数来获取图像了。我使用 imageWithContentsOfFile 来获取图像:

NSString* documentsDirectoryPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
UIImage* result =[UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.%@", documentsDirectoryPath, fileName, extension]];

然而,imageWithContentsOfFile 返回一个低质量的图像(非常模糊)。 我所有的图像都是 128*128。 我使用以下代码检测图片的大小:

NSData * imgData = UIImagePNGRepresentation(image);
NSLog(@"size : %d",[imgData length]);

我发现 imageNamed 返回的图像大小是 imageWithContentsOfFile 的 3 倍。 我疯了……救救我!非常感谢...

【问题讨论】:

  • 如何将图像复制到 Documents 目录?
  • 应用启动后为什么不能使用imageNamed获取图片?

标签: ios ios6


【解决方案1】:

UIImage reference documentation 中,您可以看到 imageNamed 和 imageWithContentsOfFile 之间的一些区别。

  • imageWithContentsOfFile 不缓存图像,也不查找视网膜显示版本 (@2x.png)。
  • imageNamed 会缓存图像并检查是否有 @2x 版本,以便在启用视网膜的设备中加载该版本。

知道了这一点,对于您的问题,我能想到的最合乎逻辑的解释是您正在使用视网膜设备并且拥有相同图像的视网膜版本 (@2x)。这可以解释为什么图像

【讨论】:

    【解决方案2】:

    我使用+ (UIImage *)imageWithContentsOfFile:(NSString *)path 来从磁盘加载图像而不缓存它们,以减少内存占用。

    从 iOS 8x 开始,这种方法似乎发生了变化。为了维护每个 iOS 版本(7x 到 9x)的功能,我在 UIImage 上使用了这个简单的类别:

    #import <UIKit/UIKit.h>
    
    @interface UIImage (ImageNamedNoCache)
    
    + (UIImage *)imageNamedNoCache:(NSString *)imageName;
    
    @end
    

    还有.m

    #import "UIImage+ImageNamedNoCache.h"
    
    #define MAIN_SCREEN                     [UIScreen mainScreen]
    #define SYSTEM_VERSION_LESS_THAN(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
    
    @implementation UIImage (ImageNamedNoCache)
    
    static NSString *bundlePath = nil;
    
    + (UIImage *)imageNamedNoCache:(NSString *)imageName
    {
        if (!bundlePath)
        {
            bundlePath = [[NSBundle mainBundle] bundlePath];
        }
    
        NSString *imgPath = [bundlePath stringByAppendingPathComponent:imageName];
    
        if (SYSTEM_VERSION_LESS_THAN(@"8.0"))
        {
            imgPath = [imgPath stringByAppendingFormat:@"@%ldx.png", (long)[MAIN_SCREEN scale]];
        }
        return [UIImage imageWithContentsOfFile:imgPath];
    }
    
    @end
    

    希望有所帮助;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-23
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多