您的位置:首页 > 其它

简单的修改项目中的头像

2016-12-21 10:56 330 查看
1. 获取手机相册和相机权限
在info.plist里面添加 Privacy - Photo Library Usage Description, 允许访问手机相册
在info.plist里面添加 Privacy - Camera Usage Description, 允许访问照相机



获取相册和相机权限

2. 遵守两个协议 UINavigationControllerDelegate, UIImagePickerControllerDelegate
遵守协议后实现代理方法,可以对选中图片进行操作

3. 给头像控件添加手势,这里注意设置 userInteractionEnabled 为 YES ,否则手势无效。
self.headImageView.userInteractionEnabled = YES;
UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeHeadImage)];
[self.headImageView addGestureRecognizer:gesture];

4. 实现手势的方法,弹出 AlertController,选择接下来的操作
- (void)changeHeadImage {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
[alert addAction:[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// 从手机相册选择图片的操作,见下文步骤5
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// 拍照操作,见下文下文步骤5
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:alert animated:YES completion:nil];
}




点击头像出现的弹框

5. 从手机相册选择图片和拍照的操作
// sourceType是一个枚举,有三种类型,设置为 UIImagePickerControllerSourceTypeCamera 时,调用相机拍照,其余两种从相册中选取图片
UIImagePickerControllerSourceTypePhotoLibrary     // 来自图库
UIImagePickerControllerSourceTypeCamera           // 来自相机
UIImagePickerControllerSourceTypeSavedPhotosAlbum // 来自相册

UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
// 设置 sourceType
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.delegate = self;
// 允许对图片进行拉伸、裁剪等编辑操作,如果设置为 NO,则直接使用原图
imagePicker.allowsEditing = YES;
[self presentViewController:imagePicker animated:YES completion:nil];

关于UIImagePickerController,戳这里,这是我之前看到的一篇博客,讲的比较详细。

6. 实现代理方法,选中图片后所做的操作放在这里,一般都是将头像控件的头像更换为新选中的头像,并将新头像上传至服务器。
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
// 更换头像控件,这里如果key值为 UIImagePickerControllerEditedImage,获取的是编辑过的图片,如果是 UIImagePickerControllerOriginalImage 则获取原图,这里还有几个 key,有兴趣的可以研究一下
self.headImageView.image = [info objectForKey:UIImagePickerControllerEditedImage];
[self dismissViewControllerAnimated:YES completion:nil];

// 新头像上传至服务器

}

补充:到这里貌似已经结束了,但是发现调用的相册和相机显示为英文,解决方法如下:
在 info.plist 里面添加 Localized resources can be mixed,类型为Boolean,改为 YES,表示允许应用程序获取框架库内语言
在 info.plist 里面添加 Localizations,类型是 Array ,添加 Chinese



相册显示英文解决方法

文/李长友同学(简书作者)

原文链接:http://www.jianshu.com/p/85c9d3d474c7

著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: