UIImagePickerController使用教程
UIImagePickerController是iOS平台上的一个系统图像选择器,用于从设备的照片库或相机中选择或拍摄图像。本文将介绍如何使用UIImagePickerController来选择和展示图像。
步骤一:导入头文件
在你的ViewController中引入和这两个协议,并且在.h文件中添加一个UIImagePickerController对象:
@interface MyViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) UIImagePickerController *imagePicker;
@end
步骤二:初始化UIImagePickerController
在你的ViewController的.m文件中,重写viewDidLoad方法并初始化UIImagePickerController对象:
- (void)viewDidLoad {
[super viewDidLoad];
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.delegate = self;
self.imagePicker.allowsEditing = YES;
}
这里设置allowsEditing属性为YES,表示可以对所选图像进行编辑,例如裁剪、旋转等操作。
步骤三:实现打开UIImagePickerController
在需要打开UIImagePickerController的地方,例如点击一个按钮时,在UIButton的Action方法中添加以下代码:
- (IBAction)selectImage:(id)sender {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *choosePhotoAction = [UIAlertAction actionWithTitle:@"Choose Photo" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:self.imagePicker animated:YES completion:nil];
}];
[alertController addAction:choosePhotoAction];
UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"Take Photo" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:self.imagePicker animated:YES completion:nil];
}];
[alertController addAction:takePhotoAction];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:cancelAction];
[self presentViewController:alertController animated:YES completion:nil];
}
这里使用UIAlertController来创建一个弹出菜单,让用户选择是从照片库中选择图像还是直接拍摄照片。在选择之后,设置UIImagePickerController的sourceType属性为所选类型,然后通过presentViewController方法打开UIImagePickerController。
步骤四:实现UIImagePickerControllerDelegate
在你的ViewController的.m文件中,实现UIImagePickerControllerDelegate协议中的方法来获取所选的图像:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];
}
在didFinishPickingMediaWithInfo方法中,获取编辑过的UIImage对象,并将其设置到实例中的UIImageView上。最后调用dismissViewControllerAnimated方法,关闭UIImagePickerController。
总结
以上就是如何使用UIImagePickerController来选择和展示图像的完整教程。希望对你有所帮助。