iOS 下载图片

//联系人:石虎QQ: 1224614774昵称:嗡嘛呢叭咪哄

iOS 下载图片_第1张图片

//

//下载图片

//  Created by石虎on 17/6/18.

//  Copyright © 2017年石虎. All rights reserved.

//

#import"ViewController.h"

/**

注意:1.只需要把以下代码拷贝到项目就可以用

2.如果需要换图片,把宏定义的URL地址换了即可

*/

//创建图片地址

#define URL  @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1497842327410&di=ac2a6e0a6bd2dcc7330f234393a4ea8e&imgtype=0&src=http%3A%2F%2Fscimg.jb51.net%2Fallimg%2F160106%2F14-160106152915B2.jpg"

@interfaceViewController()

//显示的图片

@property(strong,nonatomic)UIImageView*imageView;

//点击下载图片按钮

@property(strong,nonatomic)UIButton*downloadBtn;

@end

@implementationViewController

- (void)viewDidLoad

{

[superviewDidLoad];

//1.创建图片控件

_imageView =[[UIImageView alloc]initWithFrame:CGRectMake(30,20,self.view.frame.size.width-60,450)];

//图片背景颜色

_imageView.backgroundColor=[UIColor lightGrayColor];

//把图片添加到视图View上面

[self.view addSubview:_imageView];

//2.创建下载图片按钮

_downloadBtn=[[UIButton alloc]initWithFrame:CGRectMake(100,500,120,30)];

//按钮上面添加文字

[_downloadBtn setTitle:@"点击下载图片"forState:UIControlStateNormal];

//字体颜色

[_downloadBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

//字体背景

_downloadBtn.backgroundColor=[UIColor lightGrayColor];

//按钮点击事件

[_downloadBtn addTarget:selfaction:@selector(imageClick) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:_downloadBtn];

}

-(void)imageClick

{

NSLog(@"--->>图片按钮被点击了!!!");

_downloadBtn.backgroundColor=[UIColor redColor];

[_downloadBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

//根据字符串生成url对象

NSURL *url=[NSURL URLWithString:URL];

//创建多线程

NSThread *thread =[[NSThread alloc]initWithTarget:selfselector:@selector(downLodImage:) object:url];

//开启线程

[thread start];

}

-(void)downLodImage:(NSURL*)url

{

//根据url获取图片的二进制数据

NSData *data=[NSData dataWithContentsOfURL:url];

UIImage *imageView2=[UIImage imageWithData:data];

[selfperformSelectorOnMainThread:@selector(imageRefresh:) withObject:imageView2 waitUntilDone:NO];

}

//刷新主线程

-(void)imageRefresh:(UIImage*)image

{

//全局图片

_imageView.image=image;

}

@end

你可能感兴趣的:(iOS 下载图片)