How to blur an existing image in a UIImageView with Swift?

前端 未结 11 1970
自闭症患者
自闭症患者 2020-12-28 16:48

The setup is simple.

  • A ViewController with UIImageView that has an image assigned.
  • A UIButton that when clicked blurs the image in the UIImageView.<
11条回答
  •  滥情空心
    2020-12-28 17:32

    for those who ❤️ protocols

    protocol Bluring {
        func addBlur(_ alpha: CGFloat)
    }
    
    extension Bluring where Self: UIView {
        func addBlur(_ alpha: CGFloat = 0.5) {
            // create effect
            let effect = UIBlurEffect(style: .dark)
            let effectView = UIVisualEffectView(effect: effect)
    
            // set boundry and alpha
            effectView.frame = self.bounds
            effectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            effectView.alpha = alpha
    
            self.addSubview(effectView)
        }
    }
    
    // Conformance
    extension UIView: Bluring {}
    
    // use
    someImageview.addBlur()
    

提交回复
热议问题