iOS 下載圖片

//聯(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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容