简而言之,以下是如何使用新的图像选择器 API。
首先,您需要一个像这样声明的类,因为它将自己设置为图像选择器委托:
@interface MyClass : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate> {
UIImagePickerController* imagePicker;
}
@property(nonatomic,retain) UIImagePickerController* imagePicker;
- (IBAction) takePicture:(id)sender;
@end
调出图像选择器的方法是这样的。它在这里被声明为 an,IBAction
因此您可以直接将其连接到 Interface Builder 中的控件(如按钮)。它还会检查,如果你在 iPhone 上,它会调出相机界面,但在 iPod Touch 上,它会调出图库选择器:
#import <MobileCoreServices/UTCoreTypes.h>
...
@synthesize imagePicker = _imagePicker;
...
- (void) takePicture:(id)sender
{
if (!_imagePicker) {
self.imagePicker = [[UIImagePickerController alloc] init];
self.imagePicker.delegate = self;
}
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
NSArray* mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
self.imagePicker.mediaTypes = mediaTypes;
} else {
self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
self.imagePicker.allowsImageEditing = YES;
}
[self presentModalViewController:self.imagePicker animated:YES];
}
那么你需要这两种方法:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
// MediaType can be kUTTypeImage or kUTTypeMovie. If it's a movie then you
// can get the URL to the actual file itself. This example only looks for images.
//
NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];
// NSString* videoUrl = [info objectForKey:UIImagePickerControllerMediaURL];
// Try getting the edited image first. If it doesn't exist then you get the
// original image.
//
if (CFStringCompare((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) {
UIImage* picture = [info objectForKey:UIImagePickerControllerEditedImage];
if (!picture)
picture = [info objectForKey:UIImagePickerControllerOriginalImage];
// **You can now do something with the picture.
}
self.imagePicker = nil;
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
self.imagePicker = nil;
}