您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

搖一搖截圖實作:手勢監聽與圖像上下文的正確順序

編輯:iOS 開發綜合

「搖一搖擷取畫面」是很多 App 都有的除錯或分享功能。實作可以拆成兩半:先攔下搖動手勢,再把當前畫面渲染成圖片存進相簿。

一、監聽搖一搖

1. 讓當前視圖控制器成為第一響應者。少了這一步, motion 事件不會傳到你這裡:

// 必須先成為第一響應者,才能收到 motion 事件
[self becomeFirstResponder];

2. 覆寫 UIResponder 的 motion 方法:

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (motion == UIEventSubtypeMotionShake) {
        [self snapshot];
    }
}

實務上建議把 becomeFirstResponder 放在 viewDidAppear:,並在 viewWillDisappear: 呼叫 resignFirstResponder,否則畫面切走後仍可能收到搖動事件。另外也要記得實作 canBecomeFirstResponder 回傳 YES。

二、截圖

流程有兩個重點:順序不能顛倒——必須先開啟圖像上下文,再取得它;以及回呼方法的簽名必須固定,didFinishSavingWithError:contextInfo: 的參數型別不可自行更動。

#pragma mark - 點擊截圖按鈕
- (IBAction)snapshot {
    // 1. 開啟圖像上下文(務必先執行這步)
    UIGraphicsBeginImageContext(self.view.bounds.size);

    // 2. 取得目前上下文
    CGContextRef context = UIGraphicsGetCurrentContext();

    // 3. 把視圖圖層渲染進上下文
    [self.view.layer renderInContext:context];

    // 4. 從上下文取出圖像
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // 5. 關閉上下文
    UIGraphicsEndImageContext();

    // 6. 存入相簿
    UIImageWriteToSavedPhotosAlbum(image, self,
        @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

#pragma mark - 保存完成後的回呼(簽名固定)
- (void)image:(UIImage *)image
didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo {
    if (error) {
        NSLog(@"儲存失敗 - %@", error.localizedDescription);
    } else {
        NSLog(@"保存成功");
    }
}

幾個容易忽略的細節

  • UIGraphicsEndImageContext() 一定要呼叫。上下文是有限資源,未釋放會造成記憶體壓力,連續截圖幾次就可能被系統終止。
  • 若要截取含 Retina 解析度的清晰圖,改用 UIGraphicsBeginImageContextWithOptions(size, YES, 0.0),第三個參數傳 0 會自動採用螢幕 scale。
  • 存相簿需要使用者授權,iOS 6 之後必須在 info.plist 加上用途說明字串,否則會直接失敗。
  • renderInContext: 無法擷取 CAMetalLayer 或相機預覽等由 GPU 直接合成的内容;這類畫面需要改用 drawViewHierarchyInRect:afterScreenUpdates:。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved