創建圖片
#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];
}