iOS 線程間的通訊 (GCD),iosgcd

來源:互聯網
上載者:User

iOS 線程間的通訊 (GCD),iosgcd

 

1、從網路上 下載一張圖片將它顯示在view上

- (void)imageDownload{    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        // 圖片的網路路徑        NSURL *url = [NSURL URLWithString:@"http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"];                // 載入圖片        NSData *data = [NSData dataWithContentsOfURL:url];                // 產生圖片        UIImage *image = [UIImage imageWithData:data];                // 回到主線程        dispatch_async(dispatch_get_main_queue(), ^{            self.imageView.image = image;        });    });}

2、從網路上 下載兩張圖片,等他們兩個都下載完成後,將他們拼成一張圖片。

@interface ViewController ()@property (weak, nonatomic) IBOutlet UIImageView *imageView;/** 圖片1 */@property (nonatomic, strong) UIImage *image1;/** 圖片2 */@property (nonatomic, strong) UIImage *image2;@end

 

- (void)group{        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);    // 建立一個隊列組    dispatch_group_t group = dispatch_group_create();        // 1.下載圖片1    dispatch_group_async(group, queue, ^{        // 圖片的網路路徑        NSURL *url = [NSURL URLWithString:@"http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"];                // 載入圖片        NSData *data = [NSData dataWithContentsOfURL:url];                // 產生圖片        self.image1 = [UIImage imageWithData:data];    });        // 2.下載圖片2    dispatch_group_async(group, queue, ^{        // 圖片的網路路徑        NSURL *url = [NSURL URLWithString:@"http://pic38.nipic.com/20140228/5571398_215900721128_2.jpg"];                // 載入圖片        NSData *data = [NSData dataWithContentsOfURL:url];                // 產生圖片        self.image2 = [UIImage imageWithData:data];    });        // 3.將圖片1、圖片2合成一張新的圖片    dispatch_group_notify(group, queue, ^{        // 開啟新的圖形上下文        UIGraphicsBeginImageContext(CGSizeMake(100, 100));                // 繪製圖片        [self.image1 drawInRect:CGRectMake(0, 0, 50, 100)];        [self.image2 drawInRect:CGRectMake(50, 0, 50, 100)];                // 取得上下文中的圖片        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();                // 結束上下文        UIGraphicsEndImageContext();                // 回到主線程顯示圖片        dispatch_async(dispatch_get_main_queue(), ^{            // 4.將新圖片顯示出來             self.imageView.image = image;        });    });}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.