gpt4 book ai didi

swift - CIFilter 中的图像不会显示

转载 作者:行者123 更新时间:2023-11-30 10:51:26 24 4
gpt4 key购买 nike

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

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设置为invertedImage时,什么也没有显示,但当它设置为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!
}

最佳答案

假设您的“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!)

Update

万一,如果你是 fatalError 意味着 UIImage 不存在于 CIImage 中,所以你需要转换 UIImageCIImage

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

关于swift - CIFilter 中的图像不会显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54436327/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com