ios - 如何在将图像加载到 View Controller 之前裁剪图像

标签 ios swift xcode uiimageview uiimagepickercontroller

在我的 View Controller 中,我的 UIImageView 设置为 370x370,当我加载图像时,它当前会拉伸(stretch)以适合 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)
    }
}

关于ios - 如何在将图像加载到 View Controller 之前裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42240139/

相关文章:

IOS 在 View 之间切换

ios - ViewModel 能否返回其他 ViewModel

ios - 用于混合 V+H 的 AutoLayout 可视化语言

swift - 扫描 BLE 外设并连接到它

iphone - 使用Core Graphics绘制正方形或包含png?

objective-c - 将 libxls 与 Objective C 结合使用

iOS:UIButton 根据文本长度调整大小

ios - CFBridgeRetained 但只有 CFReleased 的 ARC 对象会发生什么?

ios - iOS 中具有多个 TableView 的屏幕的容器 View ?

ios - 解析 JSON Swift 4