根据url获取图片宽高设置网络图片

最近项目中做商铺详情,介绍信息都是从网络获取图片,并按顺序展示,我毫不犹豫的想到了SDWebImage这个框架,因为要先获取图片的宽高,再设置UIImageView的位置,但是发现图片的顺序不对,于是想到了用串行队列,并且用同步下载图片,终于可以让图片按顺序正常下载下来了,但是又发现很致命的问题,用户体验太差了,于是又在网上查资料,发现了一篇很有帮助的博客,iOS开发之 - 根据图片URL获取图片的尺寸(宽高),通过这篇博客介绍的分类,可以轻易根据图片URL得到图片的宽高,然后通过串行队列来初始化UIImageView,并将UIImageView存储在一个数组里,之后便可以直接通过for循环用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;

            // 回到主线程执行
            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];
    }
}

技术初级,欢迎大家对我提出意见!

你可能感兴趣的:(根据url获取图片宽高设置网络图片)