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

前端 未结 11 1986
自闭症患者
自闭症患者 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:35

    I made the blur in a NSObject class, so I can use this method in whole project easily.

    class Helper: NSObject
    {
        class func addBlurView(_ inView : UIView) -> UIVisualEffectView
        {
            let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
            let blurEffectView = UIVisualEffectView(effect: blurEffect)
    
            //always fill the view
            blurEffectView.frame = inView.bounds
            blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            blurEffectView.alpha = 0.5
    
            return blurEffectView
        }
    }
    

    In ViewController I made object of UIVisualEffectView. Then call the helper class method of to add blur.

    import UIKit
    
    class ViewController: UIViewController
    {
       var blurEffectView : UIVisualEffectView!
        override func viewDidLoad() {
            super.viewDidLoad()
    
          blurEffectView = Helper.addBlurView((imgView)!)
          self.imgView.addSubview(blurEffectView)
    }
    

提交回复
热议问题