博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
模仿SDWebImage实现异步加载图片
阅读量:6968 次
发布时间:2019-06-27

本文共 2107 字,大约阅读时间需要 7 分钟。

模仿SDWebImage实现异步加载图片

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

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

源码:

UIImageView+YXImageView.h

////  UIImageView+YXImageView.h//  PicDemo////  Copyright (c) 2014年 Y.X. All rights reserved.//#import 
@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本身,这个涨知识了:)

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

转载地址:http://kdisl.baihongyu.com/

你可能感兴趣的文章
Algs4-1.3.33一个双向队列Deque-双向链表实现
查看>>
Algs4-2.2.29自然的归并排序(未解决)
查看>>
shell中数组基础语法
查看>>
P1215 母亲的牛奶
查看>>
回头再看第一次项目
查看>>
有无关键字new的区别
查看>>
Hashmap,Set,Map,List,ArrayList的区别
查看>>
3.Linux 文件的压缩与打包
查看>>
JAVA分布式架构
查看>>
导入自定义模块model
查看>>
App数据分析的五大维度!
查看>>
MyBatis框架使用(一)
查看>>
MySQL索引分析
查看>>
css中常用的标签
查看>>
C++中关键字的理解--Static
查看>>
html搜索,文中的关键字变色
查看>>
Python标准库_ sys,random,time
查看>>
GP通过外部表装载数据时遇到ERROR:extra data after last expected column解决方法
查看>>
C#开发中碰到的问题------Uncaught TypeError: Cannot read property 'style' of undefined
查看>>
Android 网络编程
查看>>