来自 CIFilter 的图像不会显示



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

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

finalImage 是一个UIImageView,将其设置为显示缩放的图像有效,我可以看到它很好:

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设置为反转图像时,什么都没有显示,但是当它设置为scaledImage时,它显示得很好。

编辑:缩放图像功能:

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!
}

假设您的"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意味着UIImage不存在CIImage所以你需要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!)

相关内容

  • 没有找到相关文章

最新更新