您的位置:首页 > 移动开发 > IOS开发

iOS ---打开iPhone照相机和相册

2015-10-20 16:54 357 查看
转自:http://blog.csdn.net/riven_wn/article/details/46458293

一.添加代理

[objc] view
plaincopy

<span style="font-family:KaiTi_GB2312;font-size:18px;color:#333333;"><UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate></span>

二.添加一个显示图片的按钮

[objc] view
plaincopy

<span style="font-family:KaiTi_GB2312;font-size:18px;color:#333333;">- (void)viewDidLoad

{

[super viewDidLoad];

self.view.backgroundColor = [UIColor whiteColor];

button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

button.frame = CGRectMake(100, 100, 80, 80);

button.backgroundColor = [UIColor redColor];

[button addTarget:self action:@selector(addImage) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:button];

}

- (void)addImage

{

UIActionSheet* sheet = [[UIActionSheet alloc] initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从摄像头",@"从图片库",nil];

[sheet showInView:self.view];

}</span>

三.UIActionSheetDelegate,对应的打开照相机和相册

[objc] view
plaincopy

#pragma mark -- UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex

{

switch (buttonIndex) {

case 0:

{

//拍照

//资源类型为照相机

UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;

//判断是否有相机

if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){

UIImagePickerController *picker = [[UIImagePickerController alloc] init];

picker.delegate = self;

//设置拍照后的图片可被编辑

picker.allowsEditing = YES;

//资源类型为照相机

picker.sourceType = sourceType;

[self presentViewController:picker animated:YES completion:nil];

}else {

NSLog(@"该设备无摄像头");

}

}

break;

case 1:

{

//从相册选择

UIImagePickerController *picker = [[UIImagePickerController alloc] init];

//资源类型为图片库

picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

picker.delegate = self;

//设置选择后的图片可被编辑

picker.allowsEditing = YES;

// [self presentModalViewController:picker animated:YES];

[self presentViewController:picker animated:YES completion:nil];

}

break;

default:

break;

}

}

四.图像选取器的委托方法,选完图片后回调该方法

[objc] view
plaincopy

<span style="font-family:KaiTi_GB2312;font-size:18px;color:#333333;">#pragma Delegate method UIImagePickerControllerDelegate

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{

//当图片不为空时显示图片并保存图片

if (image != nil) {

//图片显示在界面上

[button setBackgroundImage:image forState:UIControlStateNormal];

}

//关闭相册界面

[picker dismissModalViewControllerAnimated:YES];

}</span
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: