我是UIImagePickerController,我提供關於處理照片的相關的操作,包含選取照片APP中的相片
我是UIImagePickerControllerDelegate,我定義了UIImagePickerController操作照片處理的後續作業,包含選取照片後的後續處理
UIImagePickerController說:「那我們合作吧,在我選取好照片後,在交由實作UIImagePickerControllerDelegate協定的物件,進行照片選取後的處理動作。」
第1步:建立一個名為"UIImagePickerController_UIImagePickerControllerDelegate2"的"Single View Application"專案。
第2步:加入UIImageView,並建立IBOutlet
- 加入UIImageView
- 為UIImageView設立IBOutlet - imageView
第3步:加入UIButton,並建立IBAction
- 加入UIButton,Title設定為"選照片"
- 為UIButton並設立IBAction - pickPicture
- ViewController.h檔中,實作協定UIImagePickerControllerDelegate
- 在此比較特別的是我們也會加上協定UINavigationControllerDelegate,原因是UIImagePickerController會以使用到Navigation的瀏覽模式,因此需加上,但在此範例我們不需要實作任何UINavigationControllerDelegate的方法
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (strong, nonatomic) IBOutlet UIImageView *imageView;
- (IBAction)pickPicture:(id)sender;
@end
- 於ViewController.m檔中,實作imagePickerController:didFinishPickingMediaWithInfo:方法,以將取得的相片儲存
ViewController.m
//選取相片後的處理,
//在此用以顯示選取的圖片於imageView中
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//取得選取的相片
UIImage * image = [info valueForKey:UIImagePickerControllerOriginalImage];
//設定予imageView顯示
self.imageView.image = image;
//關閉目前顯示的Controller,即UIImagePickerController
[self dismissViewControllerAnimated:YES
completion:nil];
}
- 於ViewController.m檔中,透過UIImagePickerController進行拍照
- 同時委派給self(即ViewController),以進行拍照後的處理,而ViewController因實作了UIImagePickerControllerDelegate協定,會透過imagePickerController:didFinishPickingMediaWithInfo:方法將相片儲存在照片(即iOS的照片APP)中
- (IBAction)pickPicture:(id)sender {
//建立UIImagePickerController
UIImagePickerController * controller = [[UIImagePickerController alloc] init];
//設定選取照片的來源為PhotoLibrary,即照片APP中的相片
controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
////委派給self,即目前的controller,
//以處後取得相片後的顯示相片的作業
//當然目前的controller已實作UINavigationControllerDelegate
//與 UIImagePickerControllerDelegate 2個協定
controller.delegate = self;
//轉換至UIImagePickerController,以選取照片
[self presentViewController:controller
animated:YES
completion:nil];
}
第5步:執行
- 點"選照片"後,即可在挑選特定照片後,在原先的畫面上方顯示挑選的照片
更多UIImagePickerControllerDelegate的資訊: