ios通过SDWebImage实现图片加载时的渐变效果-创新互联

先上效果图:

创新互联建站2013年开创至今,是专业互联网技术服务公司,拥有项目成都网站制作、网站设计网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元乐陵做网站,已为上家服务,为乐陵各地企业和个人服务,联系电话:028-86922220

这些图片是在我限制了网速的情况下加载的:

ios通过SDWebImage实现图片加载时的渐变效果

实现效果

思路解析

想到渐变属性的时候,自然而然的想起CATransition这个类

先看整体的实现代码:

首先找到UIImageView+WebCache.m这个文件中的- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock这个函数(大约在44行处)

修改成这个样子

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
 [self sd_cancelCurrentImageLoad];
 objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

 if (!(options & SDWebImageDelayPlaceholder)) {
  dispatch_main_async_safe(^{
   self.image = placeholder;
  });
 }

 if (url) {

  // check if activityView is enabled or not
  if ([self showActivityIndicatorView]) {
   [self addActivityIndicator];
  }

  __weak __typeof(self)wself = self;
  id  operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
   [wself removeActivityIndicator];
   if (!wself) return;
   dispatch_main_sync_safe(^{
    if (!wself) return;
    if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock)
    {
     completedBlock(image, error, cacheType, url);
     return;
    }
    else if (image) {
     CATransition *animation = [CATransition animation];
     animation.duration = .85f;
     animation.type = kCATransitionFade;
     animation.removedOnCompletion = YES;
     [wself.layer addAnimation:animation forKey:@"transition"];
     wself.image = image;
     [wself setNeedsLayout];
    } else {
     if ((options & SDWebImageDelayPlaceholder)) {
      wself.image = placeholder;
      [wself setNeedsLayout];
     }
    }
    if (completedBlock && finished) {
     completedBlock(image, error, cacheType, url);
    }
   });
  }];
  [self.layer removeAnimationForKey:@"transition"];
  [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"];
 } else {
  dispatch_main_async_safe(^{
   [self removeActivityIndicator];
   if (completedBlock) {
    NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
    completedBlock(nil, error, SDImageCacheTypeNone, url);
   }
  });
 }
}

另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网页名称:ios通过SDWebImage实现图片加载时的渐变效果-创新互联
标题路径:http://scyanting.com/article/hsihj.html