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

用 AVCaptureSession 打造自訂相機:從預覽、切鏡到拍照

編輯:iOS 開發綜合

要讓 App 拍照,最省事的作法是呼叫 UIImagePickerController 用系統相機。但當設計稿要求自訂的 OverlayView——例如取景框、手寫簽名、浮動參數面板——系統相機就撐不住了,這時必須自己組一台相機。

AVFoundation 的四個核心角色

官方文件把自訂相ography的架構說明得很清楚,需要四類物件:

  • AVCaptureDevice——代表輸入裝置,例如相機或麥克風
  • AVCaptureInput 的子類——設定從輸入裝置取得哪些連接埠的資料
  • AVCaptureOutput 的子類——管理輸出,例如存成影片檔或靜態圖
  • AVCaptureSession——負責協調輸入到輸出的資料流

先匯入 AVFoundation.framework,然後宣告需要的屬性:

@property (nonatomic, strong) AVCaptureSession            *session;         // 資料流協調者
@property (nonatomic, strong) AVCaptureDeviceInput        *videoInput;      // 輸入串流
@property (nonatomic, strong) AVCaptureStillImageOutput   *stillImageOutput;// 靜態圖輸出
@property (nonatomic, strong) AVCaptureVideoPreviewLayer  *previewLayer;    // 預覽圖層
@property (nonatomic, strong) UIBarButtonItem             *toggleButton;    // 前後鏡頭切換
@property (nonatomic, strong) UIButton                    *shutterButton;   // 快門
@property (nonatomic, strong) UIView                      *cameraShowView;  // 承載預覽層的 view

一、組裝 session

- (void)initialSession
{
    self.session = [[AVCaptureSession alloc] init];

    // 輸入:以「前鏡頭」為例
    self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self frontCamera]
                                                             error:nil];

    // 輸出:靜態圖
    self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings =
        @{ AVVideoCodecKey : AVVideoCodecJPEG };   // 以 JPEG 格式輸出
    [self.stillImageOutput setOutputSettings:outputSettings];

    // 加入前先檢查是否可添加,這是必要防護
    if ([self.session canAddInput:self.videoInput]) {
        [self.session addInput:self.videoInput];
    }
    if ([self.session canAddOutput:self.stillImageOutput]) {
        [self.session addOutput:self.stillImageOutput];
    }
}

二、取得前後鏡頭

- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position
{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if (device.position == position) {
            return device;
        }
    }
    return nil;
}

- (AVCaptureDevice *)frontCamera
{
    return [self cameraWithPosition:AVCaptureDevicePositionFront];
}

- (AVCaptureDevice *)backCamera
{
    return [self cameraWithPosition:AVCaptureDevicePositionBack];
}

三、掛上預覽圖層

在 viewWillAppear 中呼叫:

- (void)setUpCameraLayer
{
    if (_cameraAvaible == NO) return;

    if (self.previewLayer == nil) {
        self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];

        UIView  *view      = self.cameraShowView;
        CALayer *viewLayer = [view layer];
        viewLayer.masksToBounds = YES;

        [self.previewLayer setFrame:[view bounds]];
        [self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];

        [viewLayer insertSublayer:self.previewLayer below:[[viewLayer sublayers] objectAtIndex:0]];
    }
}

AVLayerVideoGravityResizeAspect 會保持畫面比例並留黑邊;若想填滿可改用 ResizeAspectFill,但要注意會裁掉部分畫面。

四、啟動與停止 session

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (self.session) {
        [self.session startRunning];
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if (self.session) {
        [self.session stopRunning];
    }
}

把 startRunning 放在 viewDidAppear 而非 viewDidLoad,是為了避免頁面還沒真正顯示就佔用相機;離開時停止則能立刻釋放硬體資源與電量。

五、切換前後鏡頭

- (void)toggleCamera
{
    NSUInteger cameraCount =
        [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    if (cameraCount <= 1) return;

    NSError *error = nil;
    AVCaptureDeviceInput *newVideoInput = nil;

    AVCaptureDevicePosition position = self.videoInput.device.position;

    if (position == AVCaptureDevicePositionBack) {
        newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self frontCamera] error:&error];
    } else if (position == AVCaptureDevicePositionFront) {
        newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self backCamera] error:&error];
    } else {
        return;
    }

    if (newVideoInput) {
        // 修改配置必須包在 beginConfiguration / commitConfiguration 之間
        [self.session beginConfiguration];
        [self.session removeInput:self.videoInput];

        if ([self.session canAddInput:newVideoInput]) {
            [self.session addInput:newVideoInput];
            self.videoInput = newVideoInput;
        } else {
            [self.session addInput:self.videoInput]; // 失敗則還原
        }

        [self.session commitConfiguration];
    } else if (error) {
        NSLog(@"切換鏡頭失敗,error = %@", error);
    }
}

beginConfiguration / commitConfiguration 這對方法用來把多個變更包成一個不可分割的批次,避免 session 處於半配置的狀態。

六、按下快門

- (void)shutterCamera
{
    AVCaptureConnection *videoConnection =
        [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];

    if (!videoConnection) {
        NSLog(@"拍照失敗");
        return;
    }

    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection
        completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {

        if (imageDataSampleBuffer == NULL) return;

        NSData *imageData =
            [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage *image = [UIImage imageWithData:imageData];
        NSLog(@"image size = %@", NSStringFromCGSize(image.size));
    }];
}

七、還需要補上的兩件事

  • 權限處理:iOS 10 之後必須在 Info.plist 加入 NSCameraUsageDescription;正式流程應先呼叫 [AVCaptureDevice requestAccessForMediaType:completionHandler:] 取得授權再組 session。
  • session 生命週期管理:startRunning 是同步阻塞的,若在前台呼叫可能卡住主線程,實務上會丟到背景佇列執行。

關於 API 的世代差異

本文使用的 AVCaptureStillImageOutput 在 iOS 10 之後已被標記為不建議使用,新的做法是以 AVCapturePhotoOutput 搭配 AVCapturePhotoCaptureSettings,能支援 HEIF、RAW、包燈與 Live Photo 等能力。核心架構(Device → Input → Session → Output)則完全沒有改變,理解這份程式碼之後遷移到新 API 會非常直接。

想要進一步擴充成錄影、手動對焦、曝光補償或浮水印,都可以在這個骨架上添加對應的 Output 與 Connection 設定。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved