iOS UIImagePickerController 图片拾取器

时间:2022-07-12 17:12:11

<UIImagePickerControllerDelegate,UINavigationControllerDelegate>


#pragma mark --图片拾取器


//获取相册


- (void)pickerFromPhotoLib{

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

    imagepicker.delegate = self;

    imagepicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    imagepicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

    imagepicker.allowsEditing = YES;

    [self presentViewController:imagepicker animated:YES completion:nil];

}


//从相机获取

-(void)pickerFromCameraSource{

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

    imagepicker.delegate = self;

    imagepicker.sourceType = UIImagePickerControllerSourceTypeCamera;

    imagepicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

    imagepicker.allowsEditing = YES;

    [self presentViewController:imagepicker animated:YES completion:nil];

}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{

   //info里面包含所有的东西,可以打印出来看一下需要什么

    [self dismissViewControllerAnimated:YES completion:nil];

}

//取消选取

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{

    [self dismissViewControllerAnimated:YES completion:nil];

}

//选择是从相册获取图片还是获取相机


- (void)changePhotolibraryOrCamera{

    UIView *view = [[UIView alloc]initWithFrame:self.view.frame];

    view.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.1];

    [self.view addSubview:view];

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction *action = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        [self pickerFromCameraSource];

        [view removeFromSuperview];

    }];

    UIAlertAction *actionPhoto = [UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        [self pickerFromPhotoLib];

        [view removeFromSuperview];

    }];

    UIAlertAction *actionCancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        [view removeFromSuperview];

    }];

    [alert addAction:action];

    [alert addAction:actionPhoto];

    [alert addAction:actionCancle];

    [self presentViewController:alert animated:YES completion:nil];

    

}