来自CIFilter的图像不会显示

时间:2019-01-30 08:36:12

标签: swift cifilter ciimage

我正在拍摄子视图的快照并将其转换为图像:

let image = UIImage(view: swiftyDraw)
let scaledImage = scaleImage(image: image, toSize: CGSize(width: 28, height:28))

finalImage是UIImageView,并将其设置为显示scaledImage即可,我可以很好地看到它:

finalImage.image = scaledImage //this works

但是,我想在显示颜色之前先将颜色反转:

let filter = CIFilter(name: "CIColorInvert")
filter!.setValue(CIImage(image: scaledImage), forKey: kCIInputImageKey)
let invertedImage = UIImage(ciImage: filter!.outputImage!)
finalImage.image = invertedImage //this does not work

当我将finalImage.image设置为reverseImage时,什么都没有显示,但是当将它设置为scaledImage时,它显示得很好。

编辑:scaleImage函数:

func scaleImage (image: UIImage, toSize size:CGSize) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(size, false, 1.0)
    image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
}

1 个答案:

答案 0 :(得分:0)

假设您的“ scaledImage”是一个UIImage,因此您可以直接获取一个CIImage,而无需创建一个新的图像。

guard let ciImage = scaledImage.ciImage, let filter = CIFilter(name: "CIColorInvert") else {
    fatalError("CIImage conversion fail")
}
//Now access the CIFilter object to filter the image
filter.setValue(ciImage, forKey: kCIInputImageKey)
finalImage.image = UIImage(ciImage: filter.outputImage!)
  

更新

如果您是fatalError,则意味着UIImageCIImage不存在,因此您需要将UIImage转换为CIImage

extension UIImage {
    var toCIImage: CIImage {
        return self.CIImage ?? CIImage(CGImage: self.CGImage!)
    }
}

guard let filter = CIFilter(name: "CIColorInvert") else {
    fatalError("CIImage conversion fail")
}

let ciImage = scaledImage.toCIImage
//Now access the CIFilter object to filter the image
filter.setValue(ciImage, forKey: kCIInputImageKey)
finalImage.image = UIImage(ciImage: filter.outputImage!)