前言:本篇博文是本人閱讀國外的IOS Programming Tutorial的一篇入門文章的學習過程總結,難度不大,因為是入門。主要是入門UIImagePickerController這個控制器,那么這個控制器是干嘛的呢?就是調用設備攝像機功能用的。到后面可能需要您在真機上測試,因為iPhone模擬器無法支持攝像機功能,運行測試會崩潰的哦。
網址:http://www.appcoda.com/ios-programming-camera-iphone-app
其實我就按照這篇博文的講解過程,自己做了一遍,也敲了一遍代碼,很快就熟悉了這個UIImagePickerController是啥玩意了。
為了幫助您了解的UIImagePickerController的使用,我們將構建一個簡單的攝像頭應用程序。該示例應用程序非常簡單:我們將有一個主窗口有一個大的UIImageView顯示選中的照片,和兩個按鈕:一個用於拍攝新照片,而另一個選擇從照片庫中的照片。
1、首先簡單的創建一個工程,然后在storyboard和對應的.m文件中添加相關的代碼,這個簡明教程沒有使用自動布局,不多說,看圖識字:
2、下面是這個ViewController.m的完整實現:
1 #import "ViewController.h" 2 3 @interface ViewController () <UIImagePickerControllerDelegate,UINavigationControllerDelegate> 4 5 @property (strong, nonatomic) IBOutlet UIImageView *imageView; 6 7 @end 8 9 @implementation ViewController 10 11 - (void)viewDidLoad { 12 [super viewDidLoad]; 13 14 // 這段代碼會自動判斷當前設備是否有攝像機功能,如果沒有,會彈窗提示 15 if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { 16 17 UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Error" 18 message:@"Device has no camera" 19 delegate:nil 20 cancelButtonTitle:@"OK" 21 otherButtonTitles: nil]; 22 23 [myAlertView show]; 24 25 } 26 } 27 - (IBAction)takePhotot:(UIButton *)sender { 28 // 創建UIImagePickerController控制器對象 29 UIImagePickerController *picker = [[UIImagePickerController alloc] init]; 30 picker.delegate = self; 31 picker.allowsEditing = YES; 32 picker.sourceType = UIImagePickerControllerSourceTypeCamera; 33 34 [self presentViewController:picker animated:YES completion:nil]; 35 } 36 - (IBAction)selectPhoto:(UIButton *)sender { 37 // 創建UIImagePickerController控制器對象 38 UIImagePickerController *picker = [[UIImagePickerController alloc] init]; 39 picker.delegate = self; 40 picker.allowsEditing = YES; 41 picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 42 43 [self presentViewController:picker animated:YES completion:nil]; 44 } 45 #pragma mark - 代理方法 46 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{ 47 UIImage* chosenImage = info[UIImagePickerControllerEditedImage]; 48 self.imageView.image = chosenImage; 49 50 [picker dismissViewControllerAnimated:YES completion:nil]; 51 } 52 -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{ 53 [picker dismissViewControllerAnimated:YES completion:nil]; 54 } 55 56 @end
就這部分代碼,別的沒有了哦。
最后用你的真機測試使用一下哦。