我正在拍摄子视图的快照并将其转换为图像:
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!)