关于UIImageView缓存加载的笔记

加载图片的两个方法:

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

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

[[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;
}

 

posted @ 2019-05-02 17:25  菜鸟工程司  阅读(240)  评论(0编辑  收藏  举报