3

我正在使用以下代码在 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 中显示它?如果是这样,我该怎么做?

4

4 回答 4

18

您在主线程上使用加载图像的代码。这将阻止用户界面。使用 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;
            });
        });
于 2013-03-29T11:52:38.053 回答
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];
于 2013-03-29T12:19:01.880 回答
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;

        }];
    }];
于 2016-05-26T07:44:08.183 回答
0

使用 SdwebImage 框架进行图像缓存

https://github.com/rs/SDWebImage

于 2015-01-25T08:19:59.787 回答