创建图片
#pragma mark - 创建 photoImageView
- (void)createphotoImageView
{
self.photoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 70, 320, 390)];
self.photoImageView.backgroundColor = [UIColor magentaColor];
// 打开交互 实现手势轻拍
self.photoImageView.userInteractionEnabled = YES;
[self addSubview:self.photoImageView];
}
实现代理(3个)
@interface RootViewController () <UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
// 绑定手势
- (void)viewDidLoad {
[super viewDidLoad];
// 轻拍手势
UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGRAction:)];
[self.rootView.photoImageView addGestureRecognizer:tapGR];
}
#pragma mark - 实现手势操作
- (void)tapGRAction:(UITapGestureRecognizer *)sender
{
NSLog(@"tap it");
// 底部弹出的控件
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"请选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相冊选取",@"拍照", nil];
// 在什么地方展示
[sheet showInView:self.rootView];
}
#pragma mark - 轻拍手势中 action 代理方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(@"%ld", buttonIndex);
// 从相冊选取或拍照
if (actionSheet.firstOtherButtonIndex == buttonIndex) {
NSLog(@"相冊");
// 相冊是否可用
if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypePhotoLibrary)]) {
UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
// 通过代理方法拿到图片
imagePickerVC.delegate = self;
// 能够对图片进行编辑(相应代理方法)
imagePickerVC.allowsEditing = YES;
// 指定 pickVC 从相冊选取
imagePickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
// 模态推出
[self presentViewController:imagePickerVC animated:YES completion:nil];
}
} else if (buttonIndex == actionSheet.firstOtherButtonIndex + 1)
{
NSLog(@"拍照");
if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
// 通过代理方法拿到图片
imagePickerVC.delegate = self;
// 能够对图片进行编辑(相应代理方法)
imagePickerVC.allowsEditing = YES;
// 指定 pickVC 从相机选取
imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
// 模态推出
[self presentViewController:imagePickerVC animated:YES completion:nil];
}
}
}
#pragma mark - 实现代理方法(拿到图片)
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
self.rootView.photoImageView.image = image;
}
#pragma mark - 取消按钮的代理方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
// 一般在 rightButton
[picker dismissViewControllerAnimated:YES completion:nil];
}