Believe in your own future, will thank yourself right now Sinner Yun

Sinner_Yun

iOS通过URL构建UIImage

很多时候我们只能得到一个URL,然后需要构建一个UIImage。 

通常情况下,我们一般都是通过SDWebImage来直接构建UIImageVIew的image,如何用URL直接构建UIImage呢? 

如下转换: 

1
2
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];  
   button.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithData:data]];

注意:此转换为同步请求,不建议使用在scrollview类中 

 

我再给一个异步请求的,通过多线程实现

1
2
3
4
5
6
7
8
9
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
        NSData * data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:UrlStr]];  
        UIImage *image = [[UIImage alloc]initWithData:data];  
        if (data != nil) {  
            dispatch_async(dispatch_get_main_queue(), ^{  
                //在这里做UI操作(UI操作都要放在主线程中执行)  
            });  
        }  
    });

 

posted on 2015-11-18 16:52  Sinner_Yun  阅读(683)  评论(0编辑  收藏  举报

导航