iPhone:下载带@2x扩展名的图像并显示在UIImageView中

4
我正在尝试从NSUrl imageURL下载图像,并通过添加@2x在UIImageView中显示它,以实现视网膜像素密度; 这将在iPhone 4或更高版本上显示。 我使用了这里的一些代码: 如何使用objective C在iOS上下载和保存文件? 当我启动它时,它在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];

将文件路径放入作用域中,而不仅仅是放在@"0@2x.png"中。


我建议使用AFNetworking。同时,dataWithContentsOfURL是同步调用,因此您应该只在后台线程上运行的代码中使用它。 - Marcin Kuptel
1个回答

4

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

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

哦,太好了!即使我修复了我的代码,它仍然不能正常工作。我的代码肯定显得过于复杂,但我认为那就是必要的。 - sudo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接