大家好,我是OB。
每天一点点。
这是一个类别 图片有缓存和压缩
- (UIImageView *)imageForUrl:(NSString *)str waitImageName:(NSString *)imgName
{
__block UIImageView * imgView = self;
NSURL * url =[NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
imgView.image = [UIImage imageNamed:imgName];
NSURLRequest * request =[NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
dispatch_async(dispatch_get_main_queue(), ^{
imgView.image = nil;
//对图片进行压缩
CGSize s ;
s.width = 2 * imgView.frame.size.width;
s.height = 2 * imgView.frame.size.height;
// 创建 context 并作为当前使用 graphics(绘制图形器) 创建一个绘制图形的上下文关系(准备)
UIGraphicsBeginImageContext(s);
UIImage * image = [UIImage imageWithData:data];
// 绘制 图片的大小
[image drawInRect:CGRectMake(0, 0, s.width, s.height)];
// 从当前的 绘制图形器 创建一个改变大小后的图片
UIImage * chagneImage = UIGraphicsGetImageFromCurrentImageContext();
// 使用 当前的context 初堆栈
UIGraphicsEndImageContext();
imgView.image = chagneImage;
});
}];
return imgView;
}