前言:本篇博文是本人阅读国外的IOS Programming Tutorial的一篇入门文章的学习过程总结,难度不大,因为是入门。主要是入门UIImagePickerController这个控制器,那么这个控制器是干嘛的呢?就是调用设备摄像机功能用的。到后面可能需要您在真机上测试,因为iPhone模拟器无法支持摄像机功能,运行测试会崩溃的哦。
网址:http://www.appcoda.com/ios-programming-camera-iphone-app
其实我就按照这篇博文的讲解过程,自己做了一遍,也敲了一遍代码,很快就熟悉了这个UIImagePickerController是啥玩意了。
为了帮助您了解的UIImagePickerController的使用,我们将构建一个简单的摄像头应用程序。该示例应用程序非常简单:我们将有一个主窗口有一个大的UIImageView显示选中的照片,和两个按钮:一个用于拍摄新照片,而另一个选择从照片库中的照片。
1、首先简单的创建一个工程,然后在storyboard和对应的.m文件中添加相关的代码,这个简明教程没有使用自动布局,不多说,看图识字:
2、下面是这个ViewController.m的完整实现:
#import "ViewController.h" @interface ViewController () <UIImagePickerControllerDelegate,UINavigationControllerDelegate> @property (strong, nonatomic) IBOutlet UIImageView *imageView; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; // 这段代码会自动判断当前设备是否有摄像机功能,如果没有,会弹窗提示
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"Device has no camera"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil]; [myAlertView show]; }
}
- (IBAction)takePhotot:(UIButton *)sender {
// 创建UIImagePickerController控制器对象
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera; [self presentViewController:picker animated:YES completion:nil];
}
- (IBAction)selectPhoto:(UIButton *)sender {
// 创建UIImagePickerController控制器对象
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; [self presentViewController:picker animated:YES completion:nil];
}
#pragma mark - 代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
UIImage* chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage; [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YES completion:nil];
} @end
就这部分代码,别的没有了哦。
最后用你的真机测试使用一下哦。