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

メインスレッドで画像をロードしているコード。これにより、UI がブロックされます。画像の読み込みに GCD async を使用します。

サンプルコードは次のとおりです。

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 に答える