Blur effect using Swift on iPhone

I am trying to implement a blur effect using UIImageView in xcode 6 (fast language), I am trying to implement it so that everything below ImageView becomes blurry.

I can't get it to work, so I ask you guys out to help me.

How can I do that?

The code I wrote so far:


class blurImage: UIImageView {

    init(frame: CGRect) {
        super.init(frame: frame)

        var blur:UIBlurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
        var effectView:UIVisualEffectView = UIVisualEffectView (effect: blur)

    }

}

+4
source share
3 answers

You need to assign a frame to view the blur and add it as a subview

class blurImage: UIImageView {

init(frame: CGRect) {
    super.init(frame: frame)

    var blur:UIBlurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
    var effectView:UIVisualEffectView = UIVisualEffectView (effect: blur)
    effectView.frame = frame
    addSubview(effectView)
}
 }
+9
source

I changed the @Kuroros class to work with storyboards

class BlurImage: UIImageView {

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    init(coder aDecoder: NSCoder!)
    {
        super.init(coder: aDecoder)

        let blur:UIBlurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
        var effectView:UIVisualEffectView = UIVisualEffectView (effect: blur)
        effectView.frame = frame
        addSubview(effectView)
    }

}
+2
source

I changed the implementation of @fabian, because when calculating the size framethere is a problem using the automatic layout. When you try to read the framedata in init(), it has not been calculated correctly yet and has a size (1000,1000) for me, but should be (420,420). Therefore, you need to read and install later. For this I used layoutSubviews. Also, the settings frame = framedid not work, because it returns the absolute position of the container, but we need the window size.

class BluredImage: UIImageView {

    var effectView:UIVisualEffectView!

    required init(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)!

        let blur:UIBlurEffect = UIBlurEffect(style: .light)
        effectView = UIVisualEffectView (effect: blur)

        addSubview(effectView)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        effectView.frame = bounds
    }

}
0
source

Source: https://habr.com/ru/post/1543795/


All Articles