zoukankan      html  css  js  c++  java
  • 图片懒加载使用

    这篇专题主要解决的问题有:

    一、照片墙中图像数据未下载时,使用默认的占位图片

    二、滑动时不加载图片,保持滑动的流畅性

    合理高效的使用占位图片,是在用户和图像之前建立一层代理,用户不直接操作图片,而将所有与图片有关的操作放在代理对象当中。

    贴一下ImageProxy的关键代码

    #import "ImageProxcy.h"
    
    @implementation ImageProxcy
    {
      UIImage *realImage;
      BOOL hasLoadImage;
    }
    - (UIImage *) image { if (realImage == nil) { realImage = [[UIImage alloc] initWithContentOfFile:_filepath]; } return realImage; }

    - (void)drawRect {
      if (realImage == nil) {
        // 此处可根据需要自定义绘制涂鸦

         if (!hasLoadImage) {
            [self image];

            [self performSelectorInBackGround:@selector(forwardLoadingThread) withObject:nil];

            hasLoadImage = YES;

        }
      }else {
        [realImage drawInRect:rect];
      }
    }

    - (void)forwardLoadingThread {
      [self image];

      [self performSelectorInBackground:@selector(setNeedsDisplay) withObject:nil];
    }

    @end

     -drawRect方法中若没加载图片,则显示自定义涂鸦,否则直接显示加载过的图片

    下面谈下如何实现滑动时不加载图片,保持滑动的流畅性?

    以tableView为例:

    cellForRowAtIndexpath:方法中,监听tableView的滑动状态

    if (tableView.isDargging == NO && tableView.isDecelerating == NO) {
       
          // tableView不滑动时,下载图片
      

           IconDownloader *dwnloader = [[IconDownloader alloc] init];

    
    

                [dwnloader startDownload:model.cover];

    
    

                dwnloader.completionHandler = ^(UIImage *resultImg) {

    
    

                    [weakSelf setImage:resultImg indexPath:indexPath];

    
    

                };

    
    }

    判定tableView停止拖拽及滑动时,下载图片,图片下载完成后,使用闭包回调设置相应cell的图片

    - (void)setImage:(UIImage *)image indexPath:(NSIndexPath *)indexpath {
        NSArray *visibleCellPath = _mTableView.indexPathsForVisibleRows;
        if ([visibleCellPath containsObject:indexpath]) {
            NBookCell *cell = [_mTableView cellForRowAtIndexPath:indexpath];
            cell.cover.image = image;
        }
        [imgCacheDic setObject:image forKey:indexpath];
    }

    闭包回调传入当前cell的indexpath,如果该cell仍然可见,则设置图片。

    最终达到的效果是,滑动时显示placeHolder,停止滑动时则加载显示网络图片。

  • 相关阅读:
    .NET Interop 工具集
    关于正弦波的算法
    Windows Phone 系列 本地数据存储
    Xaml cannot create an instance of “X”
    Windows Phone 系列 使用 MVVM绑定时无法获取当前值
    Windows Phone 系列 应用程序图标无法显示
    Windows Phone 系列 WPConnect无法上网的问题
    Windows Phone 系列 使用 Windows Phone 保存铃声任务
    WP7.5提交应用
    Windows Phone 系列 动态删除ObservableCollection
  • 原文地址:https://www.cnblogs.com/xiaoerheiwatu/p/9927088.html
Copyright © 2011-2022 走看看