3

I'm trying to add a blur effect to a layer with following code.
But it doesn't work, any advise?

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)

It just displayed the image without filter effect. I'm really confused. Thank you for any advise.

JsW
  • 1,682
  • 3
  • 22
  • 34

1 Answers1

2

This doesn't work on iOS. From the Apple documentation:

Special Considerations

This property is not supported on layers in iOS.

You'll need to do it the "long" way:

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

Please note that my Swift 4 code is untested. One or two build issues (unwrapping in particular) may be there and (of course) due to this a nil may happen at runtime. I'm providing the Swift code as a good translation of the accepted answer in the question linked to above.

Community
  • 1
  • 1
  • yeah this pretty much works! note that with this method the blur creates a fuzzy border around the content with the distance of roughly the inputRadius you input... i fixed this with a patch solution (taking it into account in the frame..) – Kev Wats Dec 19 '20 at 04:55