1. /*
  2. * @brief 图片加载通用函数
  3. * @parma imageName 图片名
  4. */
  5. - (void)imageStartLoading:(NSString *)imageName{
  6. NSURL *url = [NSURL URLWithString:imageName];
  7. if([_fileUtil hasCachedImage:url]){
  8. UIImageView *imageView = [[UIImageView alloc] init];
  9. NSString *path = [_fileUtil pathForUrl:url];
  10. imageView = [_imageLoad compressImage:MY_WIDTH/3 imageView:nil imageName:path flag:NO];
  11. [self addImage:imageView name:path];
  12. [self adjustContentSize:NO];
  13. }else{
  14. UIImageView *imageView = [[UIImageView alloc] init];
  15. NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:url, @"URL",
  16. imageView, @"imageView", nil nil];
  17. [NSThread detachNewThreadSelector:@selector(cacheImage:) toTarget:[ImageCacher shareInstance] withObject:dic];
  18. }
  19. }

这个函数的作用是为每一张网络图片开启一个下载线程,但是因为该程序用到了图片缓存的技术,所以在每次开线程下载图片的时候都会去本地缓存目录查找一下,

该图片是否已经存在,如果存在则直接加载在视图中。一般OC的线程函数有三个,NSThread, Cocoa Operations,和GCD,(想要了解三者的异同点可查看:点击打开链接),

这里我用了比较轻量级的NSThread,detachNewThreadSelector函数中所传的函数名:
cacheImage是类ImageCache中得函数,这里通过iOS开发中使用的比较多的单例模式,

得到了ImageCache的句柄,参数dic中主要存放了图片的网络地址以及imageView用来add图片进视图以及根据图片的大小压缩成合适的大小.

接下来是cacheImage函数:

  1. - (void)cacheImage:(NSDictionary*)dic{
  2. NSURL *url = [dic objectForKey:@"URL"];
  3. NSFileManager *fileManage = [NSFileManager defaultManager];
  4. NSData *data = [NSData dataWithContentsOfURL:url];
  5. NSString *fileName = [_fileUtil pathForUrl:url];
  6. if(data){
  7. [fileManage createFileAtPath:fileName contents:data attributes:nil];
  8. }
  9. UIImageView *imageView = [dic objectForKey:@"imageView"];
  10. imageView.image = [UIImage imageWithData:data];
  11. imageView = [_imageLoader compressImage:MY_WIDTH/3 imageView:imageView imageName:nil flag:YES];
  12. [self.myDelegate addImage:imageView name:fileName];
  13. [self.myDelegate adjustContentSize:NO];
  14. }

该函数用来将下载下来的图片缓存进入文件沙盒中(缓存文件可以自己定义并指定),并且按照图片的大小进行等比例压缩,固定宽度是屏幕的三分之一大小,这样一来,

图片显示就不会出现不全或失真的现象。由于ImageCache和MyScrollView是两个独立的类,所以这里通过使用ios的delegate(代理)来进行图片在scrollView上的加载,

(什么是代理模式:点击打开链接).

下面我们来看如何在沙盒中建立缓存文件夹,其实缓存文件夹跟普通的文件夹一样,只是该文件夹是专门用来存放缓存文件的而已。类代码如下所示:

  1. //
  2. //  FileUtil.m
  3. //  Test515
  4. //
  5. //  Created by silicon on 14-5-30.
  6. //  Copyright (c) 2014年 silicon. All rights reserved.
  7. //
  8. #import "FileUtil.h"
  9. @implementation FileUtil
  10. + (FileUtil *)shareInstance{
  11. static FileUtil *instance;
  12. static dispatch_once_t onceToken;
  13. dispatch_once(&onceToken, ^{
  14. instance = [[self alloc] init];
  15. });
  16. return instance;
  17. }
  18. /*
  19. @breif 创建缓存文件夹
  20. */
  21. - (void)createPathInDocumentDirectory{
  22. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  23. NSString *diskCachePath = [[[paths objectAtIndex:0] stringByAppendingPathComponent:@"ImageCache"] retain];
  24. NSLog(@"%@", diskCachePath);
  25. if(![[NSFileManager defaultManager] fileExistsAtPath:diskCachePath]){
  26. NSError *error = nil;
  27. [[NSFileManager defaultManager] createDirectoryAtPath:diskCachePath
  28. withIntermediateDirectories:YES
  29. attributes:nil
  30. error:&error];
  31. }
  32. }
  33. /*
  34. @breif     获取沙盒中文档目录
  35. @param     fileName:文件名字
  36. */
  37. - (NSString *)pathInDocumentDirectory:(NSString *)fileName{
  38. NSArray *fileArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
  39. NSUserDomainMask, YES);
  40. NSString *cacheDirectory = [fileArray objectAtIndex:0];
  41. return [cacheDirectory stringByAppendingPathComponent:fileName];
  42. }
  43. /*
  44. @breif     获取沙盒中缓存文件目录
  45. @param     fileName:文件名字
  46. */
  47. - (NSString *)pathInCacheDirectory:(NSString *)fileName{
  48. NSArray *fileArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
  49. NSUserDomainMask, YES);
  50. NSString *cacheDirectory = [fileArray objectAtIndex:0];
  51. return [cacheDirectory stringByAppendingPathComponent:fileName];
  52. }
  53. /*
  54. @breif     判断是否已经缓存
  55. @param     url:图片名称
  56. */
  57. - (BOOL)hasCachedImage:(NSURL *)url{
  58. NSFileManager *fileManager = [NSFileManager defaultManager];
  59. if([fileManager fileExistsAtPath:[self pathForUrl:url]]){
  60. return YES;
  61. }else{
  62. return NO;
  63. }
  64. }
  65. /*
  66. @breif     根据URL的給图片命名
  67. @param     url:图片url
  68. */
  69. - (NSString *)pathForUrl:(NSURL *)url{
  70. return [self pathInCacheDirectory:[NSString stringWithFormat:@"qiaoqiao-%u", [[url description] hash]]];
  71. }
  72. @end

在这次的demo中,我新加入了用户可以点击图片放大 并可以左右滑动的功能,其实实现起来很简单,我一开始为每一个ScrollView 中得ImageView都设置了tag值,并且添加了

手势(UITapGestureRecognizer),当用户点击图片时,程序可以根据点击视图的tag值来获得相应的图片是哪一张,从而可以加载。支持左右滑动的功能在新的界面中增加了

一个ScrollView,然后将下载下来的图片添加到scrollView中。代码如下

    1. //
    2. //  PhotoViewController.m
    3. //  Test515
    4. //
    5. //  Created by silicon on 14-5-22.
    6. //  Copyright (c) 2014年 silicon. All rights reserved.
    7. //
    8. #import "PhotoViewController.h"
    9. #import "ImageLoader.h"
    10. @interface PhotoViewController ()
    11. @end
    12. @implementation PhotoViewController
    13. @synthesize scrollView = _scrollView;
    14. @synthesize imageArray = _imageArray;
    15. @synthesize page = _page;
    16. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    17. {
    18. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    19. if (self) {
    20. // Custom initialization
    21. }
    22. return self;
    23. }
    24. - (void)viewDidLoad
    25. {
    26. [super viewDidLoad];
    27. // Do any additional setup after loading the view.
    28. [self.view setFrame:CGRectMake(0, 0, MY_WIDTH, MY_HEIGHT)];
    29. [self.view setBackgroundColor:[UIColor blackColor]];
    30. self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 20, MY_WIDTH, MY_HEIGHT)];
    31. _scrollView.delegate = self;
    32. _scrollView.contentSize = CGSizeMake(MY_WIDTH * [_imageArray count], MY_HEIGHT);
    33. _scrollView.showsVerticalScrollIndicator = NO;
    34. _scrollView.showsHorizontalScrollIndicator = NO;
    35. _scrollView.backgroundColor = [UIColor blackColor];
    36. _scrollView.bounces = YES;
    37. _scrollView.pagingEnabled = YES;
    38. [self.view addSubview:_scrollView];
    39. //图片添加事件响应
    40. UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closePhotoView)];
    41. tapRecognizer.delegate = self;
    42. _scrollView.userInteractionEnabled = YES;
    43. [_scrollView addGestureRecognizer:tapRecognizer];
    44. [tapRecognizer release];
    45. [self loadingImages];
    46. }
    47. - (void)viewWillAppear:(BOOL)animated{
    48. [_scrollView setContentOffset:CGPointMake([_imageArray indexOfObject:_imageName] * MY_WIDTH, 0)];
    49. }
    50. - (void)didReceiveMemoryWarning
    51. {
    52. [super didReceiveMemoryWarning];
    53. // Dispose of any resources that can be recreated.
    54. }
    55. //关闭
    56. - (void)closePhotoView{
    57. [self.view removeFromSuperview];
    58. }
    59. - (void)dealloc{
    60. [_scrollView release];
    61. [super dealloc];
    62. }
    63. - (void)loadingImages{
    64. //加载图片
    65. for(int i = 0; i < [_imageArray count]; i++){
    66. NSString *picName = [_imageArray objectAtIndex:i];
    67. UIImageView *imageV = [[ImageLoader shareInstance] compressImage:MY_WIDTH imageView:nil imageName:picName flag:NO];
    68. float width = imageV.image.size.width;
    69. float height = imageV.image.size.height;
    70. float new_width = MY_WIDTH;
    71. float new_height = (MY_WIDTH * height)/width;
    72. imageV.frame = CGRectMake(MY_WIDTH * i, 0, new_width, new_height);
    73. [_scrollView addSubview:imageV];
    74. [imageV release];
    75. }
    76. }
    77. - (void)scrollViewDidScroll:(UIScrollView *)_scrollView{
    78. }
    79. @end

IOS开发之异步加载网络图片并缓存本地实现瀑布流(二)的更多相关文章

  1. wemall app商城源码Android之ListView异步加载网络图片(优化缓存机制)

    wemall-mobile是基于WeMall的android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.本文分享wemall app商城源码Android之L ...

  2. (BUG已修改,最优化)安卓ListView异步加载网络图片与缓存软引用图片,线程池,只加载当前屏之说明

    原文:http://blog.csdn.net/java_jh/article/details/20068915 迟点出更新的.这个还有BUG.因为软引应不给力了.2.3之后 前几天的原文有一个线程管 ...

  3. android官方开源的高性能异步加载网络图片的Gridview例子

    这个是我在安卓安卓巴士上看到的资料,放到这儿共享下.这个例子android官方提供的,其中讲解了如何异步加载网络图片,以及在gridview中高效率的显示图片此代码很好的解决了加载大量图片时,报OOM ...

  4. Libgdx实现异步加载网络图片并保存到SD卡或者data/data目录下边

    Libgdx实现异步加载网络图片并保存到SD卡或者data/data目录下边,当本地有图片的时候,直接从本地读取图片,如果本地没有图片,将从服务器异步加载图片 package com.example. ...

  5. ios UIImageView异步加载网络图片

    方法1:在UI线程中同步加载网络图片 UIImageView *headview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 4 ...

  6. UIImageView异步加载网络图片

    在iOS开发过程中,经常会遇到使用UIImageView展现来自网络的图片的情况,最简单的做法如下: 去下载https://github.com/rs/SDWebImage放进你的工程里,加入头文件# ...

  7. Android批量图片加载经典系列——采用二级缓存、异步加载网络图片

    一.问题描述 Android应用中经常涉及从网络中加载大量图片,为提升加载速度和效率,减少网络流量都会采用二级缓存和异步加载机制,所谓二级缓存就是通过先从内存中获取.再从文件中获取,最后才会访问网络. ...

  8. Android批量图片加载经典系列——使用xutil框架缓存、异步加载网络图片

    一.问题描述 为提高图片加载的效率,需要对图片的采用缓存和异步加载策略,编码相对比较复杂,实际上有一些优秀的框架提供了解决方案,比如近期在git上比较活跃的xutil框架 Xutil框架提供了四大模块 ...

  9. IOS中UITableView异步加载图片的实现

    本文转载至 http://blog.csdn.net/enuola/article/details/8639404  最近做一个项目,需要用到UITableView异步加载图片的例子,看到网上有一个E ...

随机推荐

  1. Java的析构函数System的finalize()

    一个对象是由产生 到使用 到销毁的过程 即C++中 构造函数-> body->析构函数 在Java之中为了回收不需要的空间可以使用System类的finalize() class A{ p ...

  2. ThinkPHP 3.2.3 自动加载公共函数文件的方法

    方法一.加载默认的公共函数文件 在 ThinkPHP 3.2.3 中,默认的公共函数文件位于公共模块 ./Application/Common 下,访问所有的模块之前都会首先加载公共模块下面的配置文件 ...

  3. 无法启动Mysql服务,错误InnoDB: Attempted to open a previously opened tablespace.

    2013-08-04 13:48:22 760 [ERROR] InnoDB: Attempted to open a previously opened tablespace. Previous t ...

  4. SeasLog-An effective,fast,stable log extension for PHP

    github: https://github.com/Neeke/SeasLog @author Chitao.Gao [neeke@php.net] @交流群 312910117 简介 为什么使用S ...

  5. ASP.NET Global Application_Error事件中访问Session报错 解决

    报错信息:会话状态在此上下文中不可用 protected void Application_Error(object sender, EventArgs e) { //以此判断是否可用Session ...

  6. blcok的总结

    没有引用外部变量的block  为 __NSGlobalBlock__ 类型(全局block) MRC: 引用外部变量的block  为 __NSStackBlock__ 类型(栈区block)  栈 ...

  7. http://blog.csdn.net/ClementAD/article/category/6217187/2

    http://blog.csdn.net/ClementAD/article/category/6217187/2

  8. XML转换为对象操作类详解

    //XML转换为对象操作类 //一,XML与Object转换类 using System.IO; using System.Runtime.Serialization.Formatters.Binar ...

  9. PHP 5.4 on CentOS/RHEL 6.4 and 5.9 via Yum

    PHP 5.4 on CentOS/RHEL 6.4 and 5.9 via Yum PHP 5.4.16 has been released on PHP.net on 6th June 2013, ...

  10. C#.Net 调用方法,给参数赋值的一种技巧

    C#中可以给参数赋值默认值(其实这种写法有点不太好,有时会使方法的功能太复杂了)。 但是往往有多个默认参数时,有的参数需要使用默认值,有的不使用默认值,这时正常的写法就行不通了,解决方法可参照下边的代 ...