标签:
选取图片可以从设备图片库或者从照相机抓取,系统为我们提供的类UIImagePickerController就是一个图像选择器。
UIImagePickerController的主要属性是sourceType,其定义如下
按顺序说明:
UIImagePickerControllerSourceTypePhotoLibrary 为相簿
UIImagePickerControllerSourceTypeCamera 为照相机
UIImagePickerControllerSourceTypeSavedPhotosAlbum 相机胶卷
UIImagePickerController 的委托对象必须实现UINavigationControllerDelegate,UIImagePickerControllerDelegate委托协议,通过其委托对象可以看出其要继承的协议有哪几种,如下图:
UIImagePickerControllerDelegate中定义了两个方法,选择完成时调用的方法和选择取消调用的方法,
如下:
下面直接上代码:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController <UIImagePickerControllerDelegate,UINavigationControllerDelegate> @property (strong, nonatomic) UIImagePickerController *imagePicker; @property (retain, nonatomic) IBOutlet UIImageView *imageView; - (IBAction)pickPhotoLibrary:(id)sender; - (IBAction)pickPhotoCamera:(id)sender; @end
实现文件.m 代码
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)dealloc { [_imageView release]; [super dealloc]; } - (IBAction)pickPhotoLibrary:(id)sender { if (_imagePicker == nil) { _imagePicker = [[UIImagePickerController alloc] init]; } _imagePicker.delegate = self; //数据源类型为相册 _imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; [self presentViewController:_imagePicker animated:YES completion:nil]; } - (IBAction)pickPhotoCamera:(id)sender { //判断相机是否可用 if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { if (_imagePicker == nil) { _imagePicker = [[UIImagePickerController alloc] init]; } _imagePicker.delegate = self; _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; [self presentViewController:_imagePicker animated:YES completion:nil]; } else { NSLog(@"照相机不可用。"); } } - (void) imagePickerControllerDidCancel: (UIImagePickerController *) picker { _imagePicker.delegate = nil; [self dismissViewControllerAnimated:YES completion:nil]; } - (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info { //完成选择后,取出没有被编辑过的图片 UIImage *originalImage = (UIImage *) [info objectForKey: UIImagePickerControllerOriginalImage]; self.imageView.image = originalImage; self.imageView.contentMode = UIViewContentModeScaleAspectFill; _imagePicker.delegate = nil; [self dismissViewControllerAnimated:YES completion:nil]; } @end
看一下在真机中的照相机效果图:
标签:
原文地址:http://www.cnblogs.com/tianlin106/p/4561049.html