我正在尝试使用以下代码向图层添加模糊效果。
但它不起作用,有什么建议吗?
let layer = CALayer()
layer.frame = CGRect(x: 150, y: 150, width: 150, height: 150)
layer.backgroundColor = UIColor.blue.cgColor
layer.contents = UIImage(named: "D1")?.cgImage
if let filter = CIFilter(name: "CIGaussianBlur", withInputParameters: ["inputRadius": 15]) {
filter.setDefaults()
layer.filters = [filter]
}
view.layer.addSublayer(layer)
它只是显示没有滤镜效果的图像。我真的很困惑。感谢您的任何建议。
最佳答案
这在 iOS 上不起作用。来自Apple文档:
Special Considerations
This property is not supported on layers in iOS.
您需要在 "long"方式:
let ciInput = CIImage(image: UIImage(named: "D1")!)
let filter = CIFilter(name: "CIGaussianBlur", withInputParameters: ["inputImage": ciInput, "inputRadius": 15])
let ciOutput = filter?.outputImage
let ciContext = CIContext(options: nil)
let cgImage = ciContext.createCGImage(ciOutput!, from: (ciOutput?.extent)!)
layer.contents = cgImage
请注意,我的 Swift 4 代码未经测试。可能存在一两个构建问题(特别是解包),并且(当然)因此可能会在运行时发生 nil
。我提供的 Swift 代码是对上述链接问题中已接受答案的良好翻译。
关于ios - CIFilter 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47629627/