關於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;
}
相關文章
相關標籤/搜索