iOS 上處理拍照與錄影大致有兩條路:一是用 UIImagePickerController,快速又省事;二是走 AVFoundation 完全自訂介面。本文先講第一種,並示範如何順手把閃光燈當手電筒打開。
在真正叫出相機之前,務必先確認裝置支援與否,否則在模擬器上會直接失敗:
isSourceTypeAvailable::判斷該來源類型是否可用(相機/相簿)。availableMediaTypesForSourceType::查詢該來源支援的媒體類型(照片或影片)。使用 UIImagePickerController 需實作兩個委派:UINavigationControllerDelegate 與 UIImagePickerControllerDelegate。另外,要控制閃光燈必須建立一個 AVCaptureSession,並匯入 AVFoundation:
#import <UIKit/UIKit.h>
// 控制閃光燈需要 AVFoundation
#import <AVFoundation/AVFoundation.h>
@interface CameraViewController : UIViewController
<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
AVCaptureSession *_AVSession; // 控制閃光燈時使用的 session
}
@property (nonatomic, retain) AVCaptureSession *AVSession;
@end
接著在 viewDidLoad 中建立四顆按鈕:Camera(開相機)、Library(開相簿)、flashlight(開閃光燈)、close(關閃光燈)。建立按鈕的程式碼此處從略。
- (void)addCarema
{
// 模擬器不支援相機功能
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES; // 是否允許編輯
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentModalViewController:picker animated:YES];
[picker release];
} else {
// 不支援時提示使用者
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"你沒有攝像頭"
delegate:nil
cancelButtonTitle:@"Drat!"
otherButtonTitles:nil];
[alert show];
}
}
// 拍攝完成後呼叫
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// 存入相簿
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
[self dismissModalViewControllerAnimated:YES];
}
// 點擊 Cancel 後呼叫
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissModalViewControllerAnimated:YES];
}
- (void)openPicLibrary
{
// 相簿在模擬器上也可以開啟
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:picker animated:YES];
[picker release];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"無法開啟相簿"
delegate:nil
cancelButtonTitle:@"Drat!"
otherButtonTitles:nil];
[alert show];
}
}
// 選好圖片後呼叫
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
[self dismissModalViewControllerAnimated:YES];
}
原理是取得相機裝置,建立 session 並掛上輸入輸出,然後把 torchMode 設為 AVCaptureTorchModeOn,再讓 session 開始運行:
- (void)openFlashlight
{
AVCaptureDevice *device =
[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (device.torchMode == AVCaptureTorchModeOff) {
// 建立 session
AVCaptureSession *session = [[AVCaptureSession alloc] init];
// 加入裝置輸入
AVCaptureDeviceInput *input =
[AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
[session addInput:input];
// 加入視訊輸出
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
[session addOutput:output];
// 開始設定
[session beginConfiguration];
[device lockForConfiguration:nil];
[device setTorchMode:AVCaptureTorchModeOn]; // 開啟電筒
[device unlockForConfiguration];
[session commitConfiguration];
// 啟動 session
[session startRunning];
// 保留 session 參照,否則會被回收
[self setAVSession:session];
[output release];
}
}
- (void)closeFlashlight
{
[self.AVSession stopRunning];
[self.AVSession release];
}
實際跑起來會發現一個小缺點:閃光燈剛開啟時會先閃一下才持續亮起,視覺上略突兀。這是因為 session 從建立到 startRunning 之間有初始化延遲。若在意這個細節,可以先把 session 啟動好並保持運行,之後只切換 torchMode,就能做到近乎即時的開關。
另外提醒兩件事:一是 presentModalViewController:animated: 與 dismissModalViewControllerAnimated: 在 iOS 6 之後已被取代,新專案請改用 presentViewController:animated:completion:;二是存取相簿與相機在 iOS 10 之後需要在 Info.plist 中宣告 NSCameraUsageDescription 與 NSPhotoLibraryUsageDescription,否則 App 會直接崩潰。