您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

iOS 呼叫系統相機與相簿的完整做法(含閃光燈控制)

編輯:iOS 7 技巧

拍照、選照片、開關手電筒,這些是相機相關功能裡最基礎的三件事。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,它能以更高解析度取回原圖,也不必額外處理部分權限流程。

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