我使用以下代码在我的ImageView中显示图像:
imgbackBG.image = [UIImage imageWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString:[NSString stringWithFormat:@"http://%@", [test.arrImagessplash objectAtIndex:[test.arrImages count]-4]]]]];
4cing.com/mobile_app/uploads/pageicon/splash.png
问题是代码执行速度非常慢。有没有办法加载图像并更快地在ImageView中显示它?如果是这样,我该怎么做?
答案 0 :(得分:18)
您正在使用的代码在主线程上加载图像。这将阻止UI。使用GCD异步加载图像。
以下是示例代码:
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(q, ^{
/* Fetch the image from the server... */
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
/* This is the main thread again, where we set the tableView's image to
be what we just fetched. */
cell.imgview.image = img;
});
});
答案 1 :(得分:3)
从这里下载文件.....
https://github.com/nicklockwood/AsyncImageView
并按以下方式使用:
AsyncImageView *asyncImageView = [[AsyncImageView alloc]initWithFrame:CGRectMake(30,32,100, 100)];
[asyncImageView loadImageFromURL:[NSURL URLWithString:your url]];
[YourImageView addSubview:asyncImageView];
[asyncImageView release];
答案 2 :(得分:1)
Best way to used `NSOperationQueue` to load Image in background.
Here is the sample code:
NSOperationQueue *myQueue = [[NSOperationQueue alloc] init];
[myQueue addOperationWithBlock:^{
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@""]]]?:[UIImage imageNamed:@"defaultImage.png"];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
YourImageView.image = img;
}];
}];
答案 3 :(得分:0)
使用SdwebImage框架进行图像缓存