模仿SDWebImage實現非同步載入圖片

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   檔案   

模仿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本身,這個漲知識了:)

除了下載圖片,你還可以做其他動作呢:)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.