1. 程式人生 > >iOS 非同步載入網路圖片,獲取圖片真實尺寸

iOS 非同步載入網路圖片,獲取圖片真實尺寸

專案需求:
在網路上載入一組圖片的資料,並且這組圖片要按照比例展示出來

做法分析:

(1)首頁介面上要是使用的圖片控制元件的建立,這裡的高度是用設定的高度,這部分需要在主執行緒完成;
(2)第二部部分是獲取圖片的實際尺寸,這部分線上程中完成;
(3)然後需要在主執行緒重新整理frame,並使用sdweb載入圖片
參考的網址:
dispatch_group
http://blog.csdn.net/yaoliangjun306/article/details/51462444

dispatch_group_enter
http://blog.csdn.net/u011103194/article/details/50248807

根據Url獲取圖片的尺寸
http://www.oschina.net/code/snippet_2248391_53038

- (float)createImageView:(NSArray *)imageArray directionStr:(NSString *)str{

    [self removeAllSubviews];

    __block CGFloat allHeight = 0;

    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);

    dispatch_group_t group =dispatch_group_create();

    for
(int i = 0; i < [imageArray count]; i++) { 第一步:先建立一個固定高度的View,ImageView CGFloat showImageH = 600;//自定義圖片高度 //背景View UIView * backImageView = [[UIView alloc]initWithFrame:CGRectMake(0,showImageH * i,_houseFrame.size.width, showImageH)]; backImageView.backgroundColor = [UIColor
whiteColor]; //ImageView UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,_houseFrame.size.width, showImageH)]; [backImageView addSubview:imageView]; [self addSubview:backImageView]; showImageH = imageView.origin.y + imageView.height; //imageView屬性的設定 imageView.contentMode = UIViewContentModeScaleToFill; imageView.userInteractionEnabled = YES; //需要用到的Image的Url NSString *urlStr_S = [NSString stringWithFormat:@"%@%@",ImageHeaderURL,imageArray[i]]; NSURL * urlImage = [NSURL URLWithString:urlStr_S]; 第二步:根據圖片的URl獲取圖片的真是尺寸 //這裡使用group dispatch_group_async(group, queue, ^{ //這裡是獲取圖片尺寸的方法 CGSize size = [Helper getImageSizeWithURL:urlImage]; CGFloat a = size.width; CGFloat b = size.height; CGFloat space = 2; if(a > _houseFrame.size.width){ a = _houseFrame.size.width; b = size.height*(_houseFrame.size.width)/size.width; } 第三步:在group中使用非同步請求是會有問題的,這是因為要重新整理主介面了 dispatch_sync(dispatch_get_main_queue(), ^{ //NSLog(@"main-------i----%d",i); [imageView setFrame:CGRectMake(0, 0, a, b)]; [backImageView setFrame:CGRectMake(0, allHeight, _houseFrame.size.width, b)]; allHeight+=b+space; [self setFrame:CGRectMake(0, 0, _houseFrame.size.width, allHeight)]; }); //使用sdwebImage載入圖片 [imageView sd_setImageWithURL:urlImage]; }); } //等到所有的圖片的高度都計算完成了,返回介面重新整理高度 dispatch_group_notify(group, queue, ^{ //NSLog(@"dispatch_group_notify-------i----"); if(self.changeHouseType){ //檢視VR和方向的高度 self.changeHouseType(allHeight); } }); return allHeight; }