本文整理兩個實用的 iOS 圖片處理技巧:圖片壓縮,以及將整個 View 的內容截圖保存為圖片。
將壓縮邏輯封裝為類方法,方便重複調用:
+ (UIImage *)imageWithImageSimple:(UIImage *)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
使用時,可先取得螢幕截圖再壓縮至三分之一大小:
// 螢幕截圖並壓縮 UIImage *snapshot = [UIImage imageWithCGImage:[AppDelegate screenShots].CGImage scale:1 orientation:UIImageOrientationLeft]; _updataImg = [AppDelegate imageWithImageSimple:snapshot scaledToSize:CGSizeMake(snapshot.size.width / 3, snapshot.size.height / 3)];
透過 renderInContext: 將 View 的圖層渲染到上下文,即可把整個 View 的畫面截圖保存:
- (void)savetoLocal {
_moreVC.hidden = YES;
UIImage *saveimg = [self saveImage];
UIImageWriteToSavedPhotosAlbum(saveimg, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
}
- (UIImage *)saveImage {
UIGraphicsBeginImageContext(CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height - 20));
// 保存 self.view 上的內容
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
NSString *message = @"呵呵";
if (!error) {
message = @"成功保存到相冊";
} else {
message = [error description];
}
NSLog(@"message is %@", message);
}
關鍵在於 UIGraphicsBeginImageContext 建立位圖上下文、renderInContext: 將圖層內容繪製進去,再用 UIImageWriteToSavedPhotosAlbum 保存到系統相冊。這在實作「分享海報」、「保存結果圖」等功能時非常實用。