IOS开发之相册拾取器UIImagePickerController
转载自 http://blog.csdn.net/sanpintian/article/details/7411992
UIImagePickerController概述:
UIImagePickerController 类是获取选择图片和视频的用户接口。我们可以用这个controller选择我们所需要的图片和视频。对于这个类来说比较特殊,我们不能够任意定制,也不可以继承生成子类。
我们在用UIImagePickerController类的时候,只需要调用用代码实现其在什么位置显示和开始,当然我们之后可以选择所需的图片和影片,或者也可以不选择点击取消即可。
但是在我们调用接口之前,我们需要确认:
一:当前设备是否支持使用UIImagePickerController,这个时候我们需要调用isSourceTypeAvailable:方法判断。
二:查看符合的媒体类型(图片或者视频),这个时候我们调用availableMediaTypesForSourceType: 方法判断。
同时使用UIImagePickerController时,我们需要UIImagePickerControllerDelegate协议代理实现一些特定时间特定的动作。在调用摄像头的时候我们可以选择使用闪光灯,但是默认条件下对视频有10分钟的限制,需要用videoMaximumDuration属性更改默认时间,
三:之后我们设定界面媒体的属性
1:sourceType //从哪选取媒体
enum {
UIImagePickerControllerSourceTypePhotoLibrary,
UIImagePickerControllerSourceTypeCamera,
UIImagePickerControllerSourceTypeSavedPhotosAlbum
};
typedef NSUInteger UIImagePickerControllerSourceType;
2: mediaTypes
mediaTypes用来确定再picker里显示那些类型的多媒体文件,图片?视频?
+ (NSArray *)availableMediaTypesForSourceType:(UIImagePickerControllerSourceType)sourceType
一共有三个可选的代理方法UIImagePickerControllerDelegate
– imagePickerController:didFinishPickingMediaWithInfo:
– imagePickerControllerDidCancel:
– imagePickerController:didFinishPickingImage:editingInfo:
-(void) pick{
[imagePicker takePicture];
}
- (IBAction)press:(id)sender {
imagePicker = [UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.showsCameraControls = NO;
UIView* view = [UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
view.backgroundColor = [UIColor redColor];
UIButton* button = [UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
button.backgroundColor = [UIColor blueColor];
[button addTarget:self action:@selector(pick) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:button];
CGRect newFrame = CGRectMake(0.0,436,320,44);
view.frame = newFrame;
imagePicker.cameraOverlayView = view;
[self presentModalViewController:imagePicker animated:YES];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
if ([info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString*)kUTTypeImage]) {
UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
else if ([info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString*)kUTTypeMovie]) {
NSString* path = [info objectForKey:UIImagePickerControllerMediaURL] path];
UISaveVideoAtPathToSavedPhotosAlbum(path, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
}
[picker dismissModalViewControllerAnimated:YES];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissModalViewControllerAnimated:YES];
}