先上效果图:
小牺牲一下我小侄吧...
#import <UIKit/UIKit.h> @interface DemoViewController : UIViewController<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate> @property (weak, nonatomic) IBOutlet UIImageView *selectedImage; -(IBAction)imagePick:(id)sender; @end
关键代码..其它剩余部分你懂的
-(void)takeByCamera { UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.sourceType = UIImagePickerControllerSourceTypeCamera; picker.delegate = self; [self presentModalViewController:picker animated:YES]; } -(void)takeByPhotoLibrary { UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; picker.delegate = self; [self presentModalViewController:picker animated:YES]; } -(IBAction)imagePick:(id)sender { UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Please Select Photo" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"From Camera", @"From Photo Library", nil]; [actionSheet showInView:self.view]; } -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { switch (buttonIndex) { case 0: [self takeByCamera]; break; case 1: [self takeByPhotoLibrary]; break; default: break; } } -(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{ [picker dismissModalViewControllerAnimated:YES]; } -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; //Display in ImageView object (if you want to display it [self.selectedImage setImage:image]; //Take image picker off the screen (required) [self dismissModalViewControllerAnimated:YES]; } -(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo { // TempImage is a UIImage instance //bgImage is a UIImageView instance and it's connected in the IB [self.selectedImage setImage:image]; // Dismiss UIImagePickerController and release it [picker dismissModalViewControllerAnimated:YES]; }
结论:主要用的是UIImagePickerControllerDelegate这个事件委托来实现照相以及进入照片库的~