iOS UIImage 異步加載 圖片緩存壓縮 UIImageVIew分類

這是一個類別  圖片有緩存和壓縮


- (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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章