首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

iOS 截圖並保存到相冊:UIGraphicsImageRenderer 現代寫法與相容性處理

     編輯:C++ 入門

核心步驟

  1. 開啟圖形上下文(適配 Retina)。
  2. 將目標 View 的 layer 渲染進上下文。
  3. 從上下文取得 UIImage。
  4. 調用 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);
    // 可在此彈窗提示用戶
}

完整 Demo ViewController

@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

常見坑點

  • 未授權相冊:Info.plist 需添加 NSPhotoLibraryAddUsageDescription(iOS 11+)。
  • 截圖包含狀態欄/導航欄:對象為 self.view 會包含;若只想截取內容區域,傳入具體子 View。
  • 渲染 OpenGL/Metal 內容:renderInContext: 無效,需用 drawViewHierarchyInRect:afterScreenUpdates: 或專用截圖 API。
  • 大圖記憶體峰值:長頁面截圖易 OOM,分塊渲染或降低 scale。

總結

iOS 截圖保存相冊是高頻需求。掌握 UIGraphicsImageRenderer(現代)與 UIGraphicsBeginImageContextWithOptions(相容)兩套 API、UIImageWriteToSavedPhotosAlbum 回調模式、相冊權限配置,即可輕鬆實現「一鍵截圖分享」功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved