UIImageWriteToSavedPhotosAlbum 保存。- (UIImage *)snapshotOfView:(UIView *)view {
UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithBounds:view.bounds];
return [renderer imageWithActions:^(UIGraphicsImageRendererContext *ctx) {
[view.layer renderInContext:ctx.cgContext];
}];
}
優點:自動處理 scale、色彩空間、線程安全,iOS 10+ 推薦。
- (UIImage *)snapshotOfView:(UIView *)view {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
NO 表示非不透明(保留透明通道),scale 取螢幕縮放因子(2x/3x)。
- (void)saveImageToAlbum:(UIImage *)image {
UIImageWriteToSavedPhotosAlbum(image, self,
@selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
NSString *msg = error ? @"保存失敗" : @"保存成功";
NSLog(@"%@", msg);
// 可在此彈窗提示用戶
}
@interface ViewController ()
@property (nonatomic, strong) UIImageView *preview;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeContactAdd];
btn.center = CGPointMake(100, 200);
[btn addTarget:self action:@selector(capture:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
_preview = [[UIImageView alloc] initWithFrame:CGRectMake(10, 30, 300, 200)];
[self.view addSubview:_preview];
UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(20, 40, 280, 30)];
lab.text = @"截圖保存演練";
[self.view addSubview:lab];
}
- (void)capture:(id)sender {
UIImage *img = [self snapshotOfView:self.view];
_preview.image = img;
[self saveImageToAlbum:img];
}
- (UIImage *)snapshotOfView:(UIView *)view { /* 上述任一實現 */ }
- (void)saveImageToAlbum:(UIImage *)image { /* 上述實現 */ }
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo { /* 上述實現 */ }
@end
NSPhotoLibraryAddUsageDescription(iOS 11+)。self.view 會包含;若只想截取內容區域,傳入具體子 View。renderInContext: 無效,需用 drawViewHierarchyInRect:afterScreenUpdates: 或專用截圖 API。iOS 截圖保存相冊是高頻需求。掌握 UIGraphicsImageRenderer(現代)與 UIGraphicsBeginImageContextWithOptions(相容)兩套 API、UIImageWriteToSavedPhotosAlbum 回調模式、相冊權限配置,即可輕鬆實現「一鍵截圖分享」功能。