zoukankan      html  css  js  c++  java
  • 模仿SDWebImage实现异步加载图片

    模仿SDWebImage实现异步加载图片

    SDWebImage想必大家都不陌生吧,要实现它的图片异步加载功能这个还是很简单的.

    注意:此处我只实现了异步加载图片,并没有将文件缓存到本地的打算哦:)

    源码:

    UIImageView+YXImageView.h

    //
    //  UIImageView+YXImageView.h
    //  PicDemo
    //
    //  Copyright (c) 2014年 Y.X. All rights reserved.
    //
    
    #import <UIKit/UIKit.h>
    
    @interface UIImageView (YXImageView)
    
    - (void)setImageWithURL:(NSString *)url placeholderImage:(UIImage *)placeholder;
    
    @end

    UIImageView+YXImageView.m

    //
    //  UIImageView+YXImageView.m
    //  PicDemo
    //
    //  Copyright (c) 2014年 Y.X. All rights reserved.
    //
    
    #import "UIImageView+YXImageView.h"
    
    @implementation UIImageView (YXImageView)
    
    - (void)setImageWithURL:(NSString *)url placeholderImage:(UIImage *)placeholder
    {
        // 先设置placeholder
        self.image = placeholder;
        
        // 异步下载完了之后再加载新的图片
        if (url)
        {
            // 子线程下载
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
                NSData *data          = [NSURLConnection sendSynchronousRequest:request
                                                              returningResponse:nil
                                                                          error:nil];
                // 主线程更新
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (data)
                    {
                        self.image = [UIImage imageWithData:data];
                        [self setNeedsDisplay];
                    }
                });
            });
        }
    }
    
    @end

    使用的源码:

    RootViewController.m

    //
    //  RootViewController.m
    //  PicDemo
    //
    //  Copyright (c) 2014年 Y.X. All rights reserved.
    //
    
    #import "RootViewController.h"
    #import "UIImageView+YXImageView.h"
    
    @interface RootViewController ()
    
    @end
    
    @implementation RootViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
        [self.view addSubview:imageView];
        
        [imageView setImageWithURL:@"http://pic.cnitblog.com/avatar/572952/20140226185251.png"
                  placeholderImage:[UIImage imageNamed:@"1.png"]];
    }
    
    @end

    核心代码:

    GCD部分就不讲解了,关键的一步是需要重绘view本身,这个涨知识了:)

    除了下载图片,你还可以做其他操作呢:)

  • 相关阅读:
    ubuntu apt-get工作原理
    关联式容器(associative containers)
    qsort()与besearch()
    D&F学数据结构系列——插入排序
    D&F学数据结构系列——二叉堆
    Windows 系统环境变量的配置
    Python 的版本选择与安装细节
    计算机基础知识总结
    PEP 8 -- Python代码格式规则
    day57 Django补充内容(中间件其他方法、jQuery操作cookie、csrf详解和form组件简单使用)
  • 原文地址:https://www.cnblogs.com/YouXianMing/p/3862208.html
Copyright © 2011-2022 走看看