iOS图片 : 打开相机或打开相册
首先, 在应用中打开相机或者是打开相册都会有一个弹窗之类的,让用户选择到底是打开相册,还是打开相机
这里我们以弹出对话框为例
- 首先对 UIImageView 添加一个轻拍手势, 在轻拍手势的方法中创建一个 UIActionSheet 的对象
//在本类中要遵从 UIActionSheetDelegate 协议
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"获取照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册", @"拍照", nil];
[sheet showInView:self.view];
[sheet release]; 给 UIActionSheet 对象添加响应事件
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { switch (buttonIndex) { case 0: //从相册中读取 [self readImageFromAlbum]; break; case 1: //拍照 [self readImageFromCamera]; break; case 2: break; default: break; } }
//从相机中读取相片 -(void)readImageFromAlbum { UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];//创建对象 imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//(选择类型)表示仅仅从相册中选取照片 imagePicker.delegate = self;//指定代理,因此我们要实现UIImagePickerControllerDelegate, UINavigationControllerDelegate协议 imagePicker.allowsEditing = YES;//设置在相册选完照片后,是否跳到编辑模式进行图片剪裁。(允许用户编辑) [self presentViewController:imagePicker animated:YES completion:nil];//显示相册 [imagePicker release]; }
//拍照 -(void)readImageFromCamera { //判断选择的模式是否为相机模式,如果没有弹窗警告 if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; imagePicker.allowsEditing = YES;//允许编辑 imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; imagePicker.delegate = self; [self presentViewController:imagePicker animated:YES completion:nil]; [imagePicker release]; } else { //弹出窗口响应点击事件 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"未检测到摄像头" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];//警告。。确认按钮 [alert show]; [alert release]; } }
//在本类中需要遵从 UIImagePickerControllerDelegate 协议 //图片编辑完成之后触发, 显示图片在button上 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo { //参数image 就是最终选择的图片 HeaderView *header = (HeaderView*)self.tableView.tableHeaderView; [header.iconView setImage:image forState:(UIControlStateNormal)]; [self dismissViewControllerAnimated:YES completion:nil]; }
至此 , 就可以打开相机或相册了!