如何在iPhone中显示从URL下载的图像?

时间:2011-09-06 11:00:11

标签: iphone objective-c ios xcode

我正在从网址下载图片并保存。当我尝试使用ImageView在UI中显示相同的图像时,我无法做到这一点。因此,请在以下代码中建议我需要做哪些更改。

谢谢。

{

NSLog(@"Downloading...");

    UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.objectgraph.com/images/og_logo.png"]]];

    NSLog(@"%f,%f",image.size.width,image.size.height);

    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSLog(@"%@",docDir);

    NSLog(@"saving png::::%@", docDir);
    NSString *pngFilePath = [NSString stringWithFormat:@"%@/test.png",docDir];
    NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
    [data1 writeToFile:pngFilePath atomically:YES];

 NSString *sss = [docDir stringByAppendingString:@"/test.png"];

    imageView1.image = [UIImage imageNamed:sss];

    NSLog(@"------%@",sss);

[image release];

}

2 个答案:

答案 0 :(得分:2)

UIImage *theUIimage = [UIImage imageNamed:sss];
image = [[UIImageView alloc] initWithImage:theUIimage];
[imageView1 addSubview:image];

答案 1 :(得分:0)

你的imageView如何被初始化?请务必同时指定imageView.frame

e.G:

CGRect frame = CGRectMake(xPositionInView,yPositionInView,
                          image.size.width,image.size.height); 
imageView.frame = frame;