//聯(lián)系人:石虎QQ: 1224614774昵稱:嗡嘛呢叭咪哄
//
//下載圖片
//? Created by石虎on 17/6/18.
//? Copyright ? 2017年石虎. All rights reserved.
//
#import"ViewController.h"
/**
注意:1.只需要把以下代碼拷貝到項(xiàng)目就可以用
2.如果需要換圖片,把宏定義的URL地址換了即可
*/
//創(chuàng)建圖片地址
#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;
//點(diǎn)擊下載圖片按鈕
@property(strong,nonatomic)UIButton*downloadBtn;
@end
@implementationViewController
- (void)viewDidLoad
{
[superviewDidLoad];
//1.創(chuàng)建圖片控件
_imageView =[[UIImageView alloc]initWithFrame:CGRectMake(30,20,self.view.frame.size.width-60,450)];
//圖片背景顏色
_imageView.backgroundColor=[UIColor lightGrayColor];
//把圖片添加到視圖View上面
[self.view addSubview:_imageView];
//2.創(chuàng)建下載圖片按鈕
_downloadBtn=[[UIButton alloc]initWithFrame:CGRectMake(100,500,120,30)];
//按鈕上面添加文字
[_downloadBtn setTitle:@"點(diǎn)擊下載圖片"forState:UIControlStateNormal];
//字體顏色
[_downloadBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//字體背景
_downloadBtn.backgroundColor=[UIColor lightGrayColor];
//按鈕點(diǎn)擊事件
[_downloadBtn addTarget:selfaction:@selector(imageClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_downloadBtn];
}
-(void)imageClick
{
NSLog(@"--->>圖片按鈕被點(diǎn)擊了!!!");
_downloadBtn.backgroundColor=[UIColor redColor];
[_downloadBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//根據(jù)字符串生成url對象
NSURL *url=[NSURL URLWithString:URL];
//創(chuàng)建多線程
NSThread *thread =[[NSThread alloc]initWithTarget:selfselector:@selector(downLodImage:) object:url];
//開啟線程
[thread start];
}
-(void)downLodImage:(NSURL*)url
{
//根據(jù)url獲取圖片的二進(jìn)制數(shù)據(jù)
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