1
- (UIImage*)thumbnailImage:(NSString*)fileName
{
   UIImage *thumbnail = [thumbnailCache objectForKey:fileName];

   if (nil == thumbnail)
   {
      NSString *thumbnailFile = [NSString stringWithFormat:@"%@/thumbnails/%@.jpg", [[NSBundle mainBundle] resourcePath], fileName];
      thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile];
      [thumbnailCache setObject:thumbnail forKey:fileName];
   }
   return thumbnail;
}

我从http://www.alexcurylo.com/blog/2009/01/13/imagenamed-is-evil/得到了这段代码。有人可以告诉我如何使用此代码。我需要一点帮助来代替 imageNamed。

4

3 回答 3

3
NSMutableDictionary *thumbnailCache=[[NSMutableDictionary alloc]init];

然后将“缩略图”文件夹添加到您的资源文件夹然后将您的 png 放在那里

- (UIImage*)thumbnailImage:(NSString*)fileName
{
   UIImage *thumbnail = [thumbnailCache objectForKey:fileName];

   if (nil == thumbnail)
   {
      NSString *thumbnailFile = [NSString stringWithFormat:@"%@/thumbnails/%@.jpg", [[NSBundle mainBundle] resourcePath], fileName];
      thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile];
      [thumbnailCache setObject:thumbnail forKey:fileName];
   }
   return thumbnail;
}

例子

将 foo.png 添加到资源文件夹 //这里创建 UIImageView 对象然后

UIImageviewObject.image=[self thumbnailImage:@"foo.png"];
于 2011-07-08T10:49:08.300 回答
1

该代码使用 aNSMutableDictionary *thumbnailCache来缓存 UIImage 实例。该代码假定在应用程序包中,有一个目录thumbnails,其中包含缩小版本的图像。

该方法现在首先在thumbnailCache字典中查找给定图像的缩略图(它只是一个没有完整路径的文件名,例如myimage.png)。如果字典中还没有包含图像,则从thumbnails目录加载图像(使用imageWithContentsOfFile:代替imageNamed:,因为作者声称后者会造成麻烦)。然后将加载的图像存储在字典中,以便下次应用程序请求缩略图时,它可以使用已加载的实例。

要使此代码在您的应用程序中正常工作,您需要将一个thumbnails文件夹添加到您的项目中。当您将其添加到您的项目时,请务必选择“为任何添加的文件夹创建文件夹引用”而不是默认的“为任何添加的文件夹创建组”。只有这样,您才会在应用程序的主包中获得一个子目录,否则所有文件都会放在同一个顶级文件夹中。

重点是作者声称:

  • 避免[UIImage imageNamed:]
  • 相反,有一个NSMutableDictionary.
  • 在字典中查找图像。
    • 如果找到,请使用它。
    • 如果找不到,加载图像使用[UIImage imageWithContentsOfFile:]手动加载图像并将其存储在字典中。
于 2011-07-08T10:49:46.297 回答
1

thumbnailCache是在头文件中声明的 NSMutableDictionary,它应该在 .minit方法或等效方法中初始化。

如果您在资源中有图像(使用 jpg 格式,否则将代码中的 .jpg 更改为 .png),那么该行应该像

  NSString *thumbnailFile = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], fileName];

而不是使用

UIImage *thumbImage = [UIImage imageNamed:@"thumb.png"];

UIImage *thumbImage = [self thumbnailImage:@"thumb.png"];
于 2011-07-08T10:57:14.607 回答