您的位置:首页 > 产品设计 > UI/UE

UIImagePickerController---图片添加---初级使用

2015-07-15 19:03 621 查看
1.创建UIImageView

-(void)creatPhotoImageView
{
self.photoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 20, 80, 80)];
self.photoImageView.backgroundColor = [UIColor blackColor];
// 打开用户交互(默认关闭)
self.photoImageView.userInteractionEnabled = YES;
[self addSubview:self.photoImageView];
}
2.在创建的UIImageView上添加轻拍手势

// 轻拍手势
UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGRAction:)];
// 添加手势
[self.rootView.photoImageView addGestureRecognizer:tapGR];

2.1手势方法---创建UIActionSheet---设置代理(遵守代理协议)

- (void)tapGRAction:(UITapGestureRecognizer *)sender
{
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"请选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选取",@"拍照", nil];
[sheet showInView:self.rootView];
NSLog(@"%ld",sheet.cancelButtonIndex);
}

3.UIActionSheetDelegate协议代理方法---对应的按钮添加事件---给创建的UIImagePickerController设置代理(遵守代理协议UINavigationControllerDelegate,UIImagePickerControllerDelegate)

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

NSLog(@"%ld",buttonIndex);
if (buttonIndex == actionSheet.firstOtherButtonIndex) {
// 检测照片源是否可用
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {

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

// 通过代理方法拿到图片
imagePickerVC.delegate = self;
// 编辑设置默认no 代理方法key为UIImagePickerControllerEditedImage时 必须设置为YES
imagePickerVC.allowsEditing = YES;

// 指定imagePickerVC从相册获取
imagePickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

// 模态一个控制器
[self presentViewController:imagePickerVC animated:YES completion:nil];
}
}else if (buttonIndex == actionSheet.firstOtherButtonIndex + 1){

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
imagePickerVC.delegate = self;
imagePickerVC.allowsEditing = YES;

// 指定imagePickerVC从相机中获取
imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:imagePickerVC animated:YES completion:nil];
}
}
}

4.UINavigationControllerDelegate,UIImagePickerControllerDelegate协议方法---取消模态---取出图片---给对应的UIImageView设置图片

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

// picker消失 (模态消失)
[picker dismissViewControllerAnimated:YES completion:nil];

// 根据定好的key值取出图片
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
self.rootView.photoImageView.image = image;

}

这就完成了给一个UIImageView从相册或者自拍照中添加图片
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: