iosswiftblurcifilteruivisualeffectview

iOS how to make VariableBlur's CIFilter darker?


I am using the VariableBlur library in Swift to create a blur over my collection view under the status bar area as such:

I am trying to figure out how I can make the blur darker?

The library uses a CIFilter but I am not sure what to change to make it darker. I have already tried changing the UIBlurEffect(style: .regular) to use .dark but that didn't make any difference.

And the color0 on ciGradientFilter is already set to black. In fact, changing it to red or any other color doesn't make any difference.


Solution

  • The existing makeGradientImage is already making a gradient image, with color0 set to black as you have observed. The existing code uses this as a mask, but you can display this image in your own CALayer, which is added as a sibling of the backdropLayer.

    open class VariableBlurUIView: UIVisualEffectView {
    
        let darkLayer = CALayer()
        
        public init(maxBlurRadius: CGFloat = 20, direction: VariableBlurDirection = .blurredTopClearBottom, startOffset: CGFloat = 0) {
            super.init(effect: UIBlurEffect(style: .regular))
    
            // ...
    
            let gradientImage = makeGradientImage(startOffset: startOffset, direction: direction)
    
            variableBlur.setValue(maxBlurRadius, forKey: "inputRadius")
            variableBlur.setValue(gradientImage, forKey: "inputMaskImage")
            variableBlur.setValue(true, forKey: "inputNormalizeEdges")
    
            let backdropLayer = subviews.first?.layer
    
            backdropLayer?.filters = [variableBlur]
            
            darkLayer.contents = gradientImage
            darkLayer.zPosition = -1
            backdropLayer?.superLayer?.addSublayer(darkLayer)
            
            for subview in subviews.dropFirst() {
                subview.alpha = 0
            }
        }
        
        open override func layoutSublayers(of layer: CALayer) {
            darkLayer.frame = subviews.first?.layer.frame ?? .zero
        }
    
        // ...
    
    }
    

    Side-by-side comparison:

    enter image description here enter image description here