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

时间:2017-02-15 03:23:56

标签: ios swift xcode uiimageview uiimagepickercontroller

在我的视图控制器中,我的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相当新,最好将图像裁剪应用到我的代码中?

1 个答案:

答案 0 :(得分:2)

调用ImagePicker函数时,将allowEditing设置为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)
    }
}