Подтвердить что ты не робот

Как разрешить пользователю выбирать фотографию из своего рулона камеры или библиотеки фотографий?

Я делаю небольшое приложение для редактирования фотографий для удовольствия. Пользователи должны выбрать фотографию из своего рулона камеры, которая затем будет импортирована для изменения.

Как это вообще работает? Я видел много приложений, позволяющих это со стандартным контроллером, который всегда выглядит одинаково.

Возможно ли получить доступ к этой библиотеке напрямую или настроить внешний вид этого контроллера?

С чего начать?

4b9b3361

Ответ 1

Я работал над приложением, которое позволяет пользователю выбирать персональный образ. У меня было два UIButtons, которые могли помочь пользователю выбрать изображение, будь то камера или библиотека. Это что-то вроде этого:

- (void)camera {
if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
    return;
}
UIImagePickerController *picker = [[[UIImagePickerController alloc] init] autorelease];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
//Permetto la modifica delle foto
picker.allowsEditing = YES;
//Imposto il delegato
[picker setDelegate:self];

[self presentModalViewController:picker animated:YES];
}
- (void)library {
//Inizializzo la classe per la gestione della libreria immagine
UIImagePickerController *picker = [[[UIImagePickerController alloc] init] autorelease];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//Permetto la modifica delle foto
picker.allowsEditing = YES;
//Imposto il delegato
[picker setDelegate:self];

[self presentModalViewController:picker animated:YES];
}

Вам нужно реализовать UIImagePickerControllerDelegate:

@interface PickPictureViewController : UIViewController <UIImagePickerControllerDelegate>

@implementation PickPictureViewController

#pragma mark UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *pickedImage = [info objectForKey:UIImagePickerControllerEditedImage];
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
    UIImageWriteToSavedPhotosAlbum(pickedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
[self dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[self dismissModalViewControllerAnimated:YES];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{}

Надеюсь, это поможет!;)

Ответ 2

Самый простой способ сделать это - использовать UIImagePickerController в простом alertView.

Например, вы хотите, чтобы кто-то нажал на изображение своего профиля и мог установить новое изображение либо из своей камеры, либо из своей библиотеки фотографий.

введите описание изображения здесь

@IBAction func btnProfilePicTap(sender: AnyObject) {
    let picker = UIImagePickerController()
    picker.delegate = self
    let alert = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
    alert.addAction(UIAlertAction(title: "Camera", style: .Default, handler: {
        action in
        picker.sourceType = .Camera
        self.presentViewController(picker, animated: true, completion: nil)
    }))
    alert.addAction(UIAlertAction(title: "Photo Library", style: .Default, handler: {
        action in
        picker.sourceType = .PhotoLibrary
        self.presentViewController(picker, animated: true, completion: nil)
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}

Затем просто добавьте делегат, и все готово.

extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
        //use image here!
        dismissViewControllerAnimated(true, completion: nil)
    }

    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        dismissViewControllerAnimated(true, completion: nil)
    }

}

Извините, этот пример работает быстро, но я надеюсь, что это все еще помогает.

Ответ 3

Этот ответ относится только к физическому устройству!

Камера доступа:

- (void)takePhoto {

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;

[self presentViewController:picker animated:YES completion:NULL];

}

Доступ к рулону камеры:

- (void)selectPhoto {

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

[self presentViewController:picker animated:YES completion:NULL];


}

Реализация методов делегата UIImagePickerController:

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

UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.imageView.image = chosenImage;

[picker dismissViewControllerAnimated:YES completion:NULL];

}

И это:

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

[picker dismissViewControllerAnimated:YES completion:NULL];

}

Также проверьте дополнительную информацию об этой ссылке

Ответ 4

SWIFT 2.0

Благодаря Уильяму Т. это помогло мне в моем UITapGestureRecognizer

func selectPhoto(tap: UITapGestureRecognizer) {
    let picker = UIImagePickerController()
    picker.delegate = self
    let alert = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
    alert.addAction(UIAlertAction(title: "Camera", style: .Default, handler: {
        action in
        picker.sourceType = .Camera
        picker.allowsEditing = true
        self.presentViewController(picker, animated: true, completion: nil)
    }))
    alert.addAction(UIAlertAction(title: "Photo Library", style: .Default, handler: {
        action in
        picker.sourceType = .PhotoLibrary
        picker.allowsEditing = true
        self.presentViewController(picker, animated: true, completion: nil)
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}

Я добавил следующее, чтобы разрешить мне редактировать фотографию после ее выбора как в .Camera, так и в .PhotoLibrary:

picker.allowsEditing = true

Ответ 6

Вот пример приложения и обертка, которая дает вам "Снять фотографию" или "Выбрать из библиотеки", как это делает Facebook. https://github.com/fulldecent/FDTake

Ответ 7

Ответ на

@WilliamT работал очень хорошо для меня. Вот его, но обновленный для Swift 4, если кто-то все еще ищет это.

Это относится к блоку класса контроллера вида, содержащему кнопку, которую вы хотите вызвать для выбора камеры/изображения.

@IBAction func YourButtonToTriggerCamera/ImagePicker(_ sender: UIButton) {
    let picker = UIImagePickerController()
    picker.delegate = (self as UIImagePickerControllerDelegate & UINavigationControllerDelegate)
    let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: {
        action in
        picker.sourceType = .camera
        self.present(picker, animated: true, completion: nil)
    }))
    alert.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: {
        action in
        picker.sourceType = .photoLibrary
        self.present(picker, animated: true, completion: nil)
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    self.present(alert, animated: true, completion: nil)
}

Это ниже класса View Controller:

extension YourViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
        //use image here!
        dismiss(animated: true, completion: nil)
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
}