在swift中使用imagepickercontroller裁剪图像

时间:2017-04-13 22:52:08

标签: ios swift

我目前正在制作swift程序,其中涉及使用操作表从相机或照片库中选择图像的屏幕。这是完全正常的,但我希望能够从所选图像中选择一个方形部分,类似于苹果默认应用程序。我该如何实现呢?这是我的功能代码:

func chooseImage(_ sender: Any) {

    let imagePickerController = UIImagePickerController()
    imagePickerController.delegate = self

    let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet)

    actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action:UIAlertAction) in

        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imagePickerController.sourceType = .camera
            self.present(imagePickerController, animated: true, completion: nil)
        }else{
            print("Camera not available")
        }


    }))

    actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action:UIAlertAction) in
        imagePickerController.sourceType = .photoLibrary
        self.present(imagePickerController, animated: true, completion: nil)
    }))

    actionSheet.addAction(UIAlertAction(title: "Default", style: .default, handler: { (action:UIAlertAction) in
        self.avatarImageView.image = UIImage(named: "Avatar.png")


    }))

    actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

    self.present(actionSheet, animated: true, completion: nil)


}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage

    avatarImageView.image = image

    picker.dismiss(animated: true, completion: nil)
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true, completion: nil)
}
// Saves the User singleton object onto the device
static func saveData() {
    let savedData = NSKeyedArchiver.archivedData(withRootObject: User.sharedUser)
    UserDefaults.standard.set(savedData, forKey: "user")
}

4 个答案:

答案 0 :(得分:15)

您可以使用默认控件来实现图像裁剪。

self.imgPicker.allowsEditing = true

委托方法

//MARK: image picker delegate method
    //MARK:
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        var image : UIImage!

        if let img = info[UIImagePickerControllerEditedImage] as? UIImage
        {
            image = img

        }
        else if let img = info[UIImagePickerControllerOriginalImage] as? UIImage
        {
            image = img
        }


        picker.dismiss(animated: true,completion: nil)
 }

答案 1 :(得分:2)

Swift 4.0 +

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    var image : UIImage!

    if let img = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
    {
        image = img

    }
    else if let img = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
    {
        image = img
    }


    picker.dismiss(animated: true, completion: nil)
}

不要忘记将allowEditing设置为true。

另一种选择是使用TOCropViewController。它用更少的代码完成了更多工作。我发现它的优点是,它允许您更改裁剪矩形。

class ViewController: UIViewController, CropViewControllerDelegate {

    ... //your viewcontroller code

    func presentCropViewController {
        let image: UIImage = ... //Load an image

        let cropViewController = CropViewController(image: image)
        cropViewController.delegate = self
        present(cropViewController, animated: true, completion: nil)
    }

    func cropViewController(_ cropViewController: CropViewController, 
         didCropToImage image: UIImage, withRect cropRect: CGRect, angle: Int) {
        // 'image' is the newly cropped version of the original image
    }
}

答案 2 :(得分:0)

Swift 5.0

最短的声明方式:

//MARK: image picker delegate method
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

     var image : UIImage!
     if let img = info[.editedImage] as? UIImage {
         image = img
     } else if let img = info[.originalImage] as? UIImage {
         image = img
     }
     picker.dismiss(animated: true,completion: nil)
 }

按钮发送者:

@objc func buttonClicked(sender: UIButton!) {

    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary) {
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = UIImagePickerController.SourceType.photoLibrary
        picker.allowsEditing = true
        present(picker, animated: true, completion: nil)
    }
}
  • 别忘了在.plist中访问大型照片库

答案 3 :(得分:0)

- (void)cropViewController:(TOCropViewController *)cropViewController didCropToImage:(UIImage *)image withRect:(CGRect)cropRect angle:(NSInteger)angle

{

[[NSUserDefaults standardUserDefaults] setObject:UIImageJPEGRepresentation(image, 1) forKey:@"image"];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"cameraOn"];

[cropViewController dismissViewControllerAnimated:YES completion:^{

    [self performSegueWithIdentifier:@"YourSegueIdentifier" sender:self];

}];
//UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

}

对于(iOS13):使用情节提要或代码执行所有ViewController“ cropController.modalPresentationStyle = .fullScreen”。

这很好,可以轻松导航到另一个控制器。我还附有图像,以便您可以轻松了解如何更改演示文稿样式。

storyboard images