0

您能否通过示例代码提供给我,以便在代码中以编程方式创建具有特定宽度和高度的 UIImage 对象,然后在其中加载应该从 json 获取的图像(它必须是图像 URL)。

如果我使用同步网络请求来加载图片,它是否会阻止我的 UI 直到加载完成?如果是这样,解决方案是什么?

提前致谢

4

1 回答 1

1

从你的 json 数据中提取图片 URL,下载图片,然后根据需要使用图片。

NSString *imageURL = url from your json string;
NSURL *url = [NSURL URLWithString:imageURL];
UIImageView *imageView = [UIImageView alloc] initWithFrame:CGRectMake(0,0,50,75)];
[yourParentView addSubview: imageView];

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{
    UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
    dispatch_sync(dispatch_get_main_queue(), ^{
        imageView.image = image;
        CGRect frame = CGRectMake(imageView.origin.x, imageView.origin.y, image.size.width, image.size.height);
        imageView.frame = frame;
    });
});
于 2013-06-13T16:28:42.237 回答