下面介紹如何使用新的圖像拾取API一言以蔽之。
首先,你需要聲明的是這樣,因爲它的設置本身作爲圖像拾取委託類:
@interface MyClass : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate> {
UIImagePickerController* imagePicker;
}
@property(nonatomic,retain) UIImagePickerController* imagePicker;
- (IBAction) takePicture:(id)sender;
@end
,帶來了影像選擇器會去像這樣的方法。它在這裏聲明爲IBAction
,所以你可以直接將它連接到Interface Builder中的控件(如按鈕)。它還檢查,這樣如果你在iPhone上它帶來了相機接口,但在iPod觸摸它帶來了畫廊選擇器:
#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;
}
你應該接受答案。 – mk12 2009-08-18 16:13:25