English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
서론: 많은 앱들이 저의 모듈을 포함하고 있으며, 저의 모듈에서는 사용자의 프로필 이미지 등이 있으며 프로필 이미지를 변경할 수 있습니다. 따라서 이번에 iOS 개발에서 시스템 카메라를 사용하여 사진을 촬영하거나 앨범에서 사진을 가져오는 방법에 대해 간단히 소개해 드리겠습니다. 시스템 카메라나 앨범을 가져오기 위해我们需要使用到 UIImagePickerController 이 클래스를 사용해야 합니다. 아래에서는 어떻게 구현할 수 있는지 살펴보겠습니다.
먼저, UIImagePickerController 대리자의 두 가지 프로토콜을 따르는 것이 필요합니다: <UIImagePickerControllerDelegate, UINavigationControllerDelegate>입니다. 왜 두 가지 프로토콜인가요? command 키를 누른 상태에서 UIImagePickerController의 delegate를 클릭하면 실제로 이 대리자가 두 가지 프로토콜을 따르는 것을 알 수 있습니다.
#import "HeaderPhotoViewController.h" @interface HeaderPhotoViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate> @property (nonatomic, strong) UIImageView * imageView; @end @implementation HeaderPhotoViewController - (void)viewDidLoad { [super viewDidLoad]; self.navigationItem.title = @"设置头像"; self.view.backgroundColor = [UIColor whiteColor]; [self setNavigation]; [self addSubviews]; [self makeConstraintsForUI]; } #pragma mark - 设置导航 - (void)setNavigation { self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(selectPhoto:)]; } #pragma mark - 导航栏项目动作 - (void)selectPhoto:(UIBarButtonItem *)itemCamera { //创建UIImagePickerController对象,并设置代理和可编辑 UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init]; imagePicker.editing = YES; imagePicker.delegate = self; imagePicker.allowsEditing = YES; //쉐트 푸터를 생성하여 카메라 또는 앨범을 선택하도록 유도 UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"请选择打开方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet]; //相机 선택 옵션 UIAlertAction * camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { //相机를 선택할 때, UIImagePickerController 객체와 관련된 속성을 설정 imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; imagePicker.modalPresentationStyle = UIModalPresentationFullScreen; imagePicker.mediaTypes = @[(NSString *)kUTTypeImage]; imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto; //相机로 이동하여 UIImagePickerController 컨트롤러를弹出 [self presentViewController:imagePicker animated:YES completion:nil]; }] //앨범 선택 옵션 UIAlertAction * photo = [UIAlertAction actionWithTitle:@"앨범" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { //앨범을 선택할 때, UIImagePickerController 객체와 관련된 속성을 설정 imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //앨범으로 이동하여 UIImagePickerController 컨트롤러를弹出 [self presentViewController:imagePicker animated:YES completion:nil]; }] //취소 버튼 UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { [self dismissViewControllerAnimated:YES completion:nil]; }] //添加各个按钮事件 [alert addAction:camera]; [alert addAction:photo]; [alert addAction:cancel]; //弹出sheet提示框 [self presentViewController:alert animated:YES completion:nil]; } #pragma mark - add subviews - (void)addSubviews { [self.view addSubview:self.imageView]; } #pragma mark - make constraints - (void)makeConstraintsForUI { __weak typeof(self)weakSelf = self; [_imageView mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(CGSizeMake(Screen_Width, Screen_Width)); make.centerX.mas_equalTo(weakSelf.view.mas_centerX); make.centerY.mas_equalTo(weakSelf.view.mas_centerY); }] } #pragma mark - imagePickerController delegate - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info { [picker dismissViewControllerAnimated:YES completion:nil]; //가져온 이미지 UIImage * image = [info valueForKey:UIImagePickerControllerEditedImage]; _imageView.image = image; } #pragma mark - setter and getter - (UIImageView *)imageView { if (!_imageView) { _imageView = [[UIImageView alloc] init]; _imageView.backgroundColor = [UIColor greenColor]; _imageView.contentMode = UIViewContentModeScaleAspectFill; } return _imageView; } @end
OK! demo의 모든 코드가 모두 보여주었습니다. 마지막 단계는 plist 파일을 설정하는 것입니다. 이를 잊지 마세요. 그렇지 않으면 실패할 수 있습니다. plist 파일에 카메라 호출 필드 Privacy를 추가하세요 - Camera Usage Description 및 앨범 호출 필드: Privacy - Photo Library Usage Description. 모든 준비가 끝났지만, 테스트를 위해 실제 아이폰이 필요합니다. 카메라의 테스트는 실제 기기를 사용하여 테스트해야 합니다.
이것이 이 문서의 전체 내용입니다. 많은 도움이 되었기를 바랍니다. 또한,呐喊 교본에 많은 지원을 부탁드립니다.
선언: 이 문서의 내용은 인터넷에서 가져왔으며, 저작권자는 모두입니다. 내용은 인터넷 사용자가 자발적으로 기여하고 업로드한 것이며, 이 사이트는 소유권을 가지지 않으며, 인공 편집 처리를 하지 않았으며, 관련 법적 책임도 부담하지 않습니다. 저작권 침해가 의심되는 내용이 있다면, please send an email to: notice#oldtoolbag.com(보내는 이메일에서 #을 @으로 변경해 주세요. 신고를 하시고 관련 증거를 제공하시면, 실제로 확인되면 이 사이트는 즉시 저작권 침해 내용을 삭제할 것입니다.