我是UIImagePickerController,我提供關於處理照片的相關的操作,包含使用相機拍照
我是UIImagePickerControllerDelegate,我定義了UIImagePickerController操作照片處理的後續作業,包含選取照片後的後續處理
UIImagePickerController說:「那我們合作吧,在我選取好照片後,在交由實作UIImagePickerControllerDelegate協定的物件,進行照片選取後的處理動作。」
第1步:建立一個名為"UIImagePickerController_UIImagePickerControllerDelegate"的"Single View Application"專案。
第2步:加入UIButton,並建立IBAction
- 加入UIButton,Title設定為"拍照"
- 為UIButton並設立IBAction - tackPicture
- ViewController.h檔中,實作協定UIImagePickerControllerDelegate
- 在此比較特別的是我們也會加上協定UINavigationControllerDelegate,原因是UIImagePickerController會以使用到Navigation的瀏覽模式,因此需加上,但在此範例我們不需要實作任何UINavigationControllerDelegate的方法
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
- (IBAction)takePicture:(id)sender;
@end
- 於ViewController.m檔中,實作imagePickerController:didFinishPickingMediaWithInfo:方法,以將取得的相片儲存
ViewController.m
//拍攝照片後,即會呼叫此方法,
//以進行後續的存檔作業
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//取得拍攝的相片
UIImage * image = [info valueForKey:UIImagePickerControllerOriginalImage];
//儲存相片至照片中(即iOS的照片APP中)
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
//關閉拍照的UIImagePickerController
[self dismissViewControllerAnimated:YES completion:nil];
}
- 於ViewController.m檔中,透過UIImagePickerController進行拍照
- 同時委派給self(即ViewController),以進行拍照後的處理,而ViewController因實作了UIImagePickerControllerDelegate協定,會透過imagePickerController:didFinishPickingMediaWithInfo:方法將相片儲存在照片(即iOS的照片APP)中
- (IBAction)takePicture:(id)sender {
//先確認iOS裝置是否有提供攝像的功能
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
//建立UIImagePickerController
UIImagePickerController * controller =
[[UIImagePickerController alloc] init];
//設定取得相片的來源是來自於攝像鏡頭
controller.sourceType = UIImagePickerControllerSourceTypeCamera;
//委派給self,即目前的controller,
//以處後取得相片後的存檔作業
//當然目前的controller已實作UINavigationControllerDelegate
//與 UIImagePickerControllerDelegate 2個協定
controller.delegate = self;
//轉換至UIImagePickerController
[self presentViewController:controller
animated:YES
completion:nil];
}
}
第5步:"實機"執行
- 在此必須以實際來直接測試
檔案連結:UIImagePickerController_UIImagePickerControllerDelegate.zip
更多UIImagePickerControllerDelegate的資訊: