Last active
August 2, 2022 09:42
-
-
Save martinnormark/59c1523588c22fdd4b75 to your computer and use it in GitHub Desktop.
Full screen background view for iOS that adds blur and vibrancy effects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BackgroundImageView : UIView { | |
private let bgImage = UIImageView(forAutoLayout: ()) | |
private var blurView:UIVisualEffectView! | |
private var vibrancyView:UIVisualEffectView! | |
private var didSetupConstraints = false | |
var containerView: UIView? = nil { | |
willSet(container) { | |
removeContainerViewFromSuperview() | |
vibrancyView.contentView.addSubview(container!) | |
} | |
} | |
init(imageName: String) { | |
super.init() | |
let screenSize: CGRect = UIScreen.mainScreen().bounds | |
bgImage.image = UIImage(named: imageName) | |
// Scale relative to the size of the iPhone 6 Plus: http://martinnormark.com/smooth-transition-from-launch-image-to-view-controller-in-ios/ | |
bgImage.transform = CGAffineTransformMakeScale(screenSize.width / 414, screenSize.height / 736) | |
self.addSubview(bgImage) | |
let blurEffect = UIBlurEffect(style: .Dark) | |
self.blurView = UIVisualEffectView(effect: blurEffect) | |
self.blurView.setTranslatesAutoresizingMaskIntoConstraints(false) | |
self.addSubview(blurView) | |
let vibrancyEffect = UIVibrancyEffect(forBlurEffect: blurEffect) | |
vibrancyView = UIVisualEffectView(effect: vibrancyEffect) | |
vibrancyView.setTranslatesAutoresizingMaskIntoConstraints(false) | |
blurView.contentView.addSubview(vibrancyView) | |
} | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
} | |
required init(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
} | |
override func updateConstraints() { | |
if (!didSetupConstraints) { | |
bgImage.autoCenterInSuperview() | |
containerView?.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero) | |
blurView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero) | |
vibrancyView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero) | |
didSetupConstraints = true | |
} | |
super.updateConstraints() | |
} | |
private func removeContainerViewFromSuperview() { | |
if (containerView?.superview? != nil) { | |
containerView?.removeFromSuperview() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment