最近項目中做商鋪詳情,介紹信息都是從網絡獲取圖片丑蛤,并按順序展示录平,我毫不猶豫的想到了SDWebImage這個框架麻车,因為要先獲取圖片的寬高缀皱,再設置UIImageView的位置,但是發(fā)現圖片的順序不對动猬,于是想到了用串行隊列啤斗,并且用同步下載圖片,終于可以讓圖片按順序正常下載下來了赁咙,但是又發(fā)現很致命的問題钮莲,用戶體驗太差了,于是又在網上查資料彼水,發(fā)現了一篇很有幫助的博客崔拥,iOS開發(fā)之 - 根據圖片URL獲取圖片的尺寸(寬高),通過這篇博客介紹的分類凤覆,可以輕易根據圖片URL得到圖片的寬高链瓦,然后通過串行隊列來初始化UIImageView,并將UIImageView存儲在一個數組里盯桦,之后便可以直接通過for循環(huán)用SDWebImage框架來下載圖片了慈俯,就不需要自己去寫緩存之類的。
__block CGFloat width,height;
//寬度為屏幕寬度
width = ViewWidth;
__block CGFloat imageY = 0;
//高度 根據圖片寬高比設置
dispatch_queue_t shopImageQueue = dispatch_queue_create("shopImage", NULL);
for (int index = 0; index < self.shopPicArray.count; index++) {
dispatch_async(shopImageQueue, ^{
NSDictionary *imageDict = self.shopPicArray[index];
[self.imageUrlArray addObject:[NSString stringWithFormat:@"%@%@",http_url,imageDict[@"ResourcesURL"]]];
CGSize introImageSize = [UIImage getImageSizeWithURL:[NSString stringWithFormat:@"%@%@",http_url,imageDict[@"ResourcesURL"]]];
height = width * introImageSize.height / introImageSize.width;
// 回到主線程執(zhí)行
dispatch_sync(dispatch_get_main_queue(), ^(){
UIImageView *introImage = [[UIImageView alloc] init];
if (height > 0) {
introImage.frame = CGRectMake(0, imageY, width, height);
}
imageY = imageY + height;
[introImage setImage:[UIImage imageNamed:@"background_image_default"]];
[indroduceView addSubview:introImage];
[self.webImageArray addObject:introImage];
self.picHeight = imageY;
indroduceView.frame = CGRectMake(0, CGRectGetMaxY(frame), ViewWidth, imageY);
if (index == self.shopPicArray.count-1) {
[self setShopImageDetail];
}
});
});
// 然后就是用SDWebImage下載圖片
- (void)setShopImageDetail
{
for (int index = 0; index < self.webImageArray.count; index++) {
UIImageView *shopImage = self.webImageArray[index];
NSDictionary *shopPicDict = self.shopPicArray[index];
[shopImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",http_url,shopPicDict[@"ResourcesURL"]]] placeholderImage:nil options:SDWebImageRefreshCached];
}
}
技術初級拥峦,歡迎大家對我提出意見肥卡!