关于UIImageView缓存加载的笔记

加载图片的两个方法:缓存

  •  [UIImage imageNamed:]
  • [[UIImage alloc] initWithContentsOfFile: imgpath]异步

[UIImage imageNamed:] : 加载的图片会自动缓存到内存中,不适合加载大图,内存紧张的时候可能会移除图片,须要从新加载,那么在界面切换的时候可能会引发性能降低async

[[UIImage alloc] initWithContentsOfFile: imgpath]:加载图片,但未对图片进行解压,能够提早进行解压,提高加载速度.性能

    //异步加载图片
 CGSize imgViewS = imgView.bounds.size;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
      
      NSInteger index = indexPath.row;
      NSString*imgpath = _imagePaths[index];
      
      //绘制到context 提早解压图片
      UIImage *img = [[UIImage alloc] initWithContentsOfFile: imgpath];
      UIGraphicsBeginImageContextWithOptions(imgViewS  , false, 1);
    //这里也能够对图片进行压缩
      [img drawInRect:CGRectMake(0, 0, imgViewS.width, imgViewS.height)];
      img = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      //模拟延迟加载
        [NSThread sleepForTimeInterval:2];
        
      dispatch_async(dispatch_get_main_queue(), ^{
          //加载当前cell对应的图片
          if (cell.tag == index) {
              imgView.image = img;
              NSLog(@"加载图片。。。。");
          }
         
      });

二.因为每次加载都须要解压,每次解压都须要消耗内存,因此能够利用NSCahe缓存好加载过的图片

/**
 利用NSCache缓存图片

 */
- (UIImage*)loadImageIndex:(NSInteger)index {
    static NSCache *cache = nil;
    if (cache == nil) {
        cache = [[NSCache alloc] init];
        //最大缓存
//        [cache setCountLimit:1024];
        //每一个最大缓存
//        [cache setTotalCostLimit:1024];
    }
    UIImage *img = [cache objectForKey:@(index)];
    if (img) {
        return [img isKindOfClass:[NSNull class]]?nil:img;
    }
    //设置占位,防止图片屡次加载
    [cache setObject:[NSNull null] forKey:@(index)];
   
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *imgpath = self.imagePaths[index];
        UIImage *loadimg = [UIImage imageWithContentsOfFile:imgpath];
        //渲染图片到contenx
        UIGraphicsBeginImageContextWithOptions(loadimg.size, false, 1);
        [loadimg drawAtPoint:CGPointZero];
        
        loadimg = UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
        dispatch_async(dispatch_get_main_queue(), ^{
            //缓存图片
            [cache setObject:loadimg forKey:@(index)];
        
            NSIndexPath *indexpath =  [NSIndexPath indexPathForRow:index inSection:0];
            UICollectionViewCell *cell = [self.collectView cellForItemAtIndexPath:indexpath];
            if (cell != nil) {
                UIImageView*imgV =  [cell.contentView viewWithTag:111];
                imgV.image = loadimg;
            }
            
        });
    });
    //未加载
    return nil;
}
相关文章
相关标签/搜索