IOS開發之小執行個體--使用UIImagePickerController建立一個簡單的相機應用程式,uiimagepicker裁剪
前言:本篇博文是本人閱讀國外的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 ViewController10 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:nil20 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
就這部分代碼,別的沒有了哦。
最後用你的真機測試使用一下哦。