iOS,Swift,UIImagePicker允许编辑裁剪工具删除透明度。有修复吗?

时间:2017-01-26 12:52:39

标签: ios swift image cocoa-touch uiimagepickercontroller

当我从UIImagePicker获得具有透明背景的PNG图像时,它会插入具有透明背景的图像,如下所示:

enter image description here

当我设置:

imagePicker.allowsEditing = true

它允许我在UIImagePicker提供的视图中按预期裁剪

但是当我按下“选择”时,它会返回带有黑色而不是透明背景的图像,如下所示:

enter image description here

两个结果之间的唯一变化是设置

imagePicker.allowsEditing = true

并在应用中裁剪图片。

裁剪时是否有办法保持透明度或至少将黑色变为白色?

我在网上搜索过,没有提到我能看到的内容。

代码:

 func showImagePicker() {
    imagePicker.allowsEditing = true
    imagePicker.sourceType = .photoLibrary

    present(imagePicker, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
        compImageView?.contentMode = .scaleAspectFit
        compImageView?.backgroundColor = UIColor.clear
        compImageView?.image = pickedImage

    }

    dismiss(animated: true, completion: nil)
}

2 个答案:

答案 0 :(得分:4)

默认情况下,UIImagePickerController会删除已编辑图像中的Alpha通道。要获得透明度,您必须自己编辑图像。像这样实现委托方法:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {


        if let cropRect = info[UIImagePickerControllerCropRect] as? CGRect {
            if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
                let imageRef: CGImage = image.cgImage!.cropping(to: cropRect)!

                let image1: UIImage = UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)

                imageView.image = image1
                picker.dismiss(animated: true, completion: nil)

            }

        }

    }

答案 1 :(得分:0)

请尝试此代码。

import MobileCoreServices //importing for mediaType kUTTypeImage


func showImagePicker() {

    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
    let mediaTypes: Array<AnyObject> = [kUTTypeImage]
    imagePicker.mediaTypes = mediaTypes as! [String]
    imagePicker.allowsEditing = true
    self.present(imagePicker, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    if picker.sourceType == UIImagePickerControllerSourceType.photoLibrary {

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

            dismiss(animated: true, completion: nil)
            compImageView?.image = image
        }
    }
}