一.添加代理
<span style="font-family:KaiTi_GB2312;font-size:18px;color:#333333;"><UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate></span>
二.添加一个显示图片的按钮
<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,对应的打开照相机和相册
#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;
}
}
四.图像选取器的委托方法,选完图片后回调该方法
<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>