調用相機時,需要引入兩個代理協議:UIImagePickerControllerDelegate 與 UINavigationControllerDelegate,否則設定 delegate 時會出現不相容的警告。
設定 delegate 時若出現「Assigning to 'id<UINavigationControllerDelegate, UIImagePickerControllerDelegate>' from incompatible type」的警告,通常是 strong 引用不相容所致。把對應的屬性從 strong 改為 weak 即可消除:
// 修改前 @property (nonatomic) UIImagePickerController *imgPickerController; // 修改後 @property (nonatomic, weak) UIImagePickerController *imgPickerController;
也就是說,Property 若不指定引用類型,預設是 strong,此處改為 weak 即可解除警告。另外,Xcode 偶爾無法即時消除警告,得手動到 Product → Clean 一下。
先把 sourceType 設為相機,並判斷相機是否可用(例如 iPod 沒有相機),不可用時可退回使用相簿:
-(void)takePhotoAction:(UIButton *)sender {
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];
}
}
iPhone 上直接用相簿來源:
-(void)openPhotosAction:(UIButton *)sender {
UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
}
pickerImage.delegate = self;
pickerImage.allowsEditing = NO;
[self presentViewController:pickerImage animated:YES completion:nil];
}
iPad 上則需用 UIPopoverController 以彈出視窗方式呈現:
-(void)ipadPicker {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = NO;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:picker];
[popover presentPopoverFromRect:CGRectMake(0, 0, 300, 300) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
若裝置旋轉後位置定位錯誤,需在父視圖控制器的 didRotateFromInterfaceOrientation: 中重新設定 rect 並再次呼叫 presentPopoverFromRect 方法。
有時需要以相機畫面為背景,在其上加入自訂控件。隱藏系統控制項並放大預覽即可達到全屏效果:
-(void)onClickbutton:(id)sender {
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
[controller setSourceType:UIImagePickerControllerSourceTypeCamera];
[controller setShowsCameraControls:NO]; // 隱藏系統控制項
CGAffineTransform cameraTransform = CGAffineTransformMakeScale(1.25, 1.25);
controller.cameraViewTransform = cameraTransform;
[self presentViewController:controller animated:YES completion:nil];
}
若要讓自訂相機顯示中文,可在專案設定的 Custom iOS Target Properties 中,把 Localization native development region 設為 China。掌握這些技巧,就能在不同裝置與場景下靈活調用相機與相簿。