拍照、選照片、開關手電筒,這些是相機相關功能裡最基礎的三件事。iOS 把它們都收在 UIImagePickerController 與 AVCaptureDevice 兩個入口底下。本文用一個包含四顆按鈕的範例頁面,把相機、相簿與閃光燈的呼叫流程串起來。
viewDidLoad 中用迴圈一口氣產生「調用相機」、「調用圖片庫」、「打開閃關燈」、「關閉閃光燈」四顆按鈕,各自綁定對應方法:
#import "CameraViewController.h"
@interface CameraViewController ()
@end
@implementation CameraViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *arr = @[@"調用相機", @"調用圖片庫", @"打開閃關燈", @"關閉閃光燈"];
for (int i = 0; i < 4; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, (100 + 10) * i + 50, 100, 100);
[button setTitle:arr[i] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
if (i == 0) {
[button addTarget:self action:@selector(addCarema)
forControlEvents:UIControlEventTouchUpInside];
} else if (i == 1) {
[button addTarget:self action:@selector(openPicLibrary)
forControlEvents:UIControlEventTouchUpInside];
} else if (i == 2) {
[button addTarget:self action:@selector(openFlashlight)
forControlEvents:UIControlEventTouchUpInside];
} else if (i == 3) {
[button addTarget:self action:@selector(closeFlashlight)
forControlEvents:UIControlEventTouchUpInside];
}
[self.view addSubview:button];
}
}
調用相機前務必先檢查硬體是否支援——模擬器沒有相機,直接 present 會得到一個空畫面。這裡透過 isSourceTypeAvailable 判斷,不支援時用 UIAlertView 提示:
-(void)addCarema
{
// 判斷能否開啟相機(模擬器不支援)
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES; // 是否允許裁切編輯
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:nil];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"你沒有攝像頭" delegate:nil
cancelButtonTitle:@"Drat!" otherButtonTitles:nil, nil];
[alert show];
}
}
使用者完成拍攝或選好照片後,會回呼到 delegate 方法。info 字典裡的 UIImagePickerControllerOriginalImage 就是原始影像,而 EditedImage 則是裁切後的版本,可依 allowsEditing 的設定選用:
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// 取得照片
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// 存入相簿
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
[self dismissViewControllerAnimated:YES completion:nil];
}
// 按下 Cancel 時
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
流程與相機幾乎一樣,只把 sourceType 換成 PhotoLibrary。相簿在模擬器上是可以正常使用的:
-(void)openPicLibrary
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:nil];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"無法開啟相簿" delegate:nil
cancelButtonTitle:@"Drat!" otherButtonTitles:nil, nil];
[alert show];
}
}
閃光燈走的是 AVCaptureDevice 這條路。取得 video 類型的預設裝置後,先確認 hasTorch,再透過 lockForConfiguration 鎖定設定、切換 torchMode、最後解鎖:
-(void)openFlashlight
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch]) {
[device lockForConfiguration:nil];
[device setTorchMode:AVCaptureTorchModeOn];
[device unlockForConfiguration];
}
}
-(void)closeFlashlight
{
[self.AVSession stopRunning];
}
此處修正了原始範例的兩個問題:開啟手電筒應該是 AVCaptureTorchModeOn(原本誤寫為 Off,等於什麼也沒做);關閉手電筒若要走 AVCaptureSession,就該把 torchMode 設回 Off 或乾脆 stopRunning,兩種方式擇一即可,而 AVSession 也需自行宣告為屬性並設定好輸入來源。
三個容易忽略的地方。第一,delegate 一定要設,否則拍完照畫面不會自動關閉;第二,正式專案請改用 PHPickerViewController 或搭配 PhotosUI,並在 Info.plist 裡補上 NSCameraUsageDescription 與 NSPhotoLibraryUsageDescription 的用途說明,缺少時 App 會直接閃退;第三,UIImagePickerController 自 iOS 14 起已被標記為不建議使用,新專案建議改用 PHPicker,它能以更高解析度取回原圖,也不必額外處理部分權限流程。