我的应用程序必须从 http 服务器加载图像并将其显示到 UIImageView
我该怎么做?
我试过这个:
NSString *temp = [NSString alloc];
[temp stringwithString:@"http://192.168.1.2x0/pic/LC.jpg"]
temp=[(NSString *)CFURLCreateStringByAddingPercentEscapes(
nil,
(CFStringRef)temp,
NULL,
NULL,
kCFStringEncodingUTF8)
autorelease];
NSData *dato = [NSData alloc];
dato=[NSData dataWithContentsOfURL:[NSURL URLWithString:temp]];
pic = [pic initWithImage:[UIImage imageWithData:dato]];
此代码在 View 的 viewdidload 中,但没有显示任何内容!
服务器正在运行,因为我可以从中加载 xml 文件。但我无法显示该图像!
我需要以编程方式加载图像,因为它必须根据传递的参数进行更改!
先感谢您。
安东尼奥
最佳答案
应该是:
NSURL * imageURL = [NSURL URLWithString:@"http://192.168.1.2x0/pic/LC.jpg"];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];
一旦你有了 image
变量,你就可以通过它的 image
属性将它放入 UIImageView
中,即:
myImageView.image = image;
//OR
[myImageView setImage:image];
如果您需要转义原始字符串中的特殊字符,您可以这样做:
NSString * urlString = [@"http://192.168.1.2x0/pic/LC.jpg" stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL * imageURL = [NSURL URLWithString:urlString];
....
如果您以编程方式创建UIImageView
,您可以:
UIImageView * myImageView = [[UIImageView alloc] initWithImage:image];
[someOtherView addSubview:myImageView];
[myImageView release];
关于iphone - Xcode iPhone编程: Loading a jpg into a UIImageView from URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2510223/