在項目開發的過程當中,咱們常常會使用的iPhone 或者 iPad 的拍照功能,好比給用戶設置頭像,通常都會用到拍照功能。咱們能夠使用UIImagePickerController 類來調用iPhone的攝像頭進行拍照或者錄視頻。iOS 已經爲咱們封裝好了UIImagePickerController ,使用很簡單,讓咱們不用花費不少時間就能夠調用拍照功能。使用UIImagePickerController時,須要實現UIImagePickerController協議。 app
在xib中添加一個按鈕,綁定按鈕的響應事件,在響應事件中添加以下代碼: atom
UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera; //判斷是否有攝像頭 if(![UIImagePickerController isSourceTypeAvailable:sourceType]) { sourceType = UIImagePickerControllerSourceTypePhotoLibrary; } UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; imagePickerController.delegate = self; // 設置委託 imagePickerController.sourceType = sourceType; imagePickerController.allowsEditing = YES; [self presentViewController:imagePickerController animated:YES completion:nil]; //須要以模態的形式展現 [imagePickerController release];記得要實現UIImagePickerControllerDelegate 中 的- ( void )imagePickerController:( UIImagePickerController *)picker didFinishPickingMediaWithInfo:( NSDictionary *)info 和
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker 兩個方法,分別時拍照完成的時候調用 和 取消拍照的時候調用。代碼以下: spa
#pragma mark - #pragma mark UIImagePickerController Method //完成拍照 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { [picker dismissViewControllerAnimated:YES completion:^{}]; UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage]; if (image == nil) image = [info objectForKey:UIImagePickerControllerOriginalImage]; [self performSelector:@selector(saveImage:) withObject:image]; } //用戶取消拍照 -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [picker dismissViewControllerAnimated:YES completion:nil]; } //將照片保存到disk上 -(void)saveImage:(UIImage *)image { NSData *imageData = UIImagePNGRepresentation(image); if(imageData == nil) { imageData = UIImageJPEGRepresentation(image, 1.0); } NSDate *date = [NSDate date]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyyMMddHHmmss"]; _fileName = [[[formatter stringFromDate:date] stringByAppendingPathExtension:@"png"] retain]; NSURL *saveURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:_fileName]; [imageData writeToURL:saveURL atomically:YES]; }