話不多說,直接開始:
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
相冊顯示英文解決方法