使用SDWebImage加载图片问题总结

实际项目中遇到以下问题:需要从服务器加载若干尺寸未知的图片到APP中作为UIButton的资源图片显示。考虑到的解决方案有:正好项目中有在使用SDWebImage,可以更方便的实现异步请求资源、缓存、
在主线程更换图片这些操作,因此决定继续使用SDWebImage 对UIButton的扩展。所以有了以下方案:
2.首先将UIButton 初始化加载到view中,使用
- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:
(SDWebImageCompletionBlock)completedBlock;

为button设置图片,在回调block中,对button重新设置frame,可以使用较为简洁的代码实现对所有未知尺寸的图片资源的使用。具体实现如下:

 __block  CGFloat imageHeight = HEIGHT(self.imageScrollView) - 2*margin;
       __block CGFloat currentWidth = 0;

        for (int i =0;i<[_imageURLs count]; i++) {
            NSString *imageURL = [host stringByAppendingString:[_imageURLs objectAtIndex:i]];

            UIButton *imageButton =[[UIButton alloc]init];
            [imageButton addTarget:self action:@selector(imageButtonOnSelected:) forControlEvents:UIControlEventTouchUpInside];
            imageButton.tag = i;
            [imageButton sd_setImageWithURL:[NSURL URLWithString:imageURL] forState:UIControlStateNormal completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL){

                NSLog(@"%@,%@,%ld,%@",image,error,(long)cacheType,imageURL);

                CGRect frame = imageButton.frame;
                if (image.size.height<image.size.width) {
                    frame.size.width = imageHeight;
                    frame.size.height = frame.size.width/image.size.width*image.size.height;
                }
                imageButton.frame = frame;
                [imageButton setTransform:CGAffineTransformMakeRotation(M_PI/2)];
                 imageButton.center = CGPointMake(WIDTH(imageButton)/2 +currentWidth, HEIGHT(_imageScrollView)/2);
                [_imageScrollView addSubview:imageButton];
                 currentWidth +=(WIDTH(imageButton) +margin);
                imageWidth = WIDTH(imageButton);
                [_imageScrollView setContentSize:CGSizeMake(currentWidth, imageHeight)];
            }];

        }

查看SDWebImage代码可以看到 completedBlock 实在回调主线程,因此可以直接在对调中对UI进行更新。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值