【问题标题】:iPhone: Downloading Image then Displaying in UIImageView with @2x ExtensioniPhone:使用@2x 扩展下载图像然后在 UIImageView 中显示
【发布时间】:2013-05-26 08:50:30
【问题描述】:

我正在尝试从 NSUrl imageURL 下载图像,并通过添加 @2x; 将其显示在具有视网膜像素密度的 UIImageView 中。这将在 iPhone 4 或更高版本上显示。我在这里使用了一些代码:How do I download and save a file locally on iOS using objective C?

当我启动它时,它在 imageView 上什么也没有显示,最后 NSLog 行打印出图像的一些非常小的尺寸,表明它并没有真正下载一个。除了错误检查非常糟糕之外,我的代码还有什么问题?

- (void) presentImage: (NSURL*) imageURL{
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
NSLog([imageURL description]);

if ( imageData )
{
    NSArray   *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString  *documentsDirectory = [paths objectAtIndex:0];

    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"0@2x.png"];
    [imageData writeToFile:filePath atomically:YES];
}
else NSLog(@"Error when loading image!!!");

imageData = [NSData dataWithContentsOfFile:@"0@2x.png"];
UIImage *image = [[UIImage alloc] initWithData: imageData];
NSLog(@"%f1 x %f2", image.size.width, image.size.height);
[self.imageView setImage: image];

}

编辑:好的,我解决了这个问题。我觉得我好笨。我应该放的

imageData = [NSData dataWithContentsOfFile:@filePath];

并将 filePath 放入范围内,而不是仅放入 @"0@2x.png"。

【问题讨论】:

  • 我建议使用 AFNetworking。此外,dataWithContentsOfURL 是一个同步调用,因此您应该只在后台线程上运行的代码中使用它。

标签: ios iphone objective-c uiimageview retina-display


【解决方案1】:

我认为你把问题复杂化了。使用这个方法:

+ (UIImage *)imageWithData:(NSData *)data scale:(CGFloat)scale

当你有视网膜图像时,将比例设置为2.0

-(void)presentImage:(NSURL*)imageURL {
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *image = [UIImage imageWithData:imageData scale:2.0];
    [self.imageView setImage: image];
}

【讨论】:

  • 哦,完美!即使在我修复了我的代码之后,它仍然无法正常工作。我的代码确实看起来过于复杂,但我认为这就是它所需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-08
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
  • 2018-02-26
  • 1970-01-01
相关资源
最近更新 更多