項目需求:
在網絡上加載一組圖片的數據,並且這組圖片要按照比例展示出來
做法分析:
(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;
}