YYKit组件学习- YYWebImage

YYWebImage调用方法:

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, hotelRatingView.frame.origin.y+hotelRatingView.frame.size.height+10, 200, 100)];
[self.view addSubview:imageView];

NSURL *url = [NSURL URLWithString:@"http://ppt360.com/background/UploadFiles_6733/201012/2010122016330331.jpg"];
[imageView yy_setImageWithURL:url
                  placeholder:nil
                      options:YYWebImageOptionSetImageWithFadeAnimation
                     progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                         NSLog(@"图片的size :%ld  ,期望的尺寸:%ld",(long)receivedSize,(long)expectedSize);
                     }
                    transform:^UIImage *(UIImage *image, NSURL *url) {
                        image = [image yy_imageByResizeToSize:CGSizeMake(100, 100) contentMode:UIViewContentModeCenter];
                        return [image yy_imageByRoundCornerRadius:10];
                    }
                   completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) {
                       [imageView setImage:image];
                       if (from == YYWebImageFromDiskCache) {
                           NSLog(@"load from disk cache");
                       }
  }];
  为什么在completion我就更新UI了?难道不用考虑是不是在主线程做UI操作吗?请看源码:
    dispatch_async(dispatch_get_main_queue(), ^{
                if (setImage && self) {
                    if (showFade) {
                        CATransition *transition = [CATransition animation];
                        transition.duration = stage == YYWebImageStageFinished ? _YYWebImageFadeTime : _YYWebImageProgressiveFadeTime;
                        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
                        transition.type = kCATransitionFade;
                        [self.layer addAnimation:transition forKey:_YYWebImageFadeAnimationKey];
                    }
                    self.image = image;
                }
                if (completion) completion(image, url, from, stage, error);
});
   已经设计好了,所以不用你考虑了。由此类推,如果你的AFNetworking封装,如果请求相应之后没有返回主线程,那么就别在子线程中去创建UI。当然这样做本来就不合理。

效果如下

image.png

你可能感兴趣的:(YYKit组件学习- YYWebImage)