如何在将图像加载到视图控制器之前裁剪图像

How can I crop an image before loading it to the view controller

在我的视图控制器中,我的 UIImageView 设置为 370x370,当我加载图像时,它当前会拉伸以适合 ImageView。

这是我目前用于选择图像的内容:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    // Runs when user is picking image from library
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        self.previewImageView.image = pickedImage
        self.selectImageButton.isEnabled = false
        self.selectImageButton.isHidden = true
        uploadImage(image: pickedImage)
        picker.dismiss(animated: true, completion: nil)
    }
}

我是 Swift 的新手,最好的方法是在我的代码中实现图像裁剪?

调用ImagePicker函数时,将allowsEditing设置为true:

self.imagePicker.allowsEditing = true
self.imagePicker.sourceType = .camera
self.present(self.imagePicker, animated: true, completion: nil)

另一个选项,如果你想要更多的自定义,你可以使用这个库:https://github.com/TimOliver/TOCropViewController

然后在 didFinishPickingMediaWithInfo 中,你做这样的事情:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage{
        dismiss(animated: true, completion: nil)
        let cropVC = TOCropViewController(image: pickedImage)
        cropVC.delegate = self
        cropVC.aspectRatioPickerButtonHidden = true
        cropVC.aspectRatioPreset = .presetSquare
        cropVC.aspectRatioLockEnabled = true
        cropVC.resetAspectRatioEnabled = false
        self.present(cropVC, animated: true, completion: nil)
    }
}