Skip to content

Instantly share code, notes, and snippets.

@igorleonovich
Last active June 24, 2024 10:10
Show Gist options
  • Save igorleonovich/aff3c97f5f756dad057ee73d03fce40f to your computer and use it in GitHub Desktop.
Save igorleonovich/aff3c97f5f756dad057ee73d03fce40f to your computer and use it in GitHub Desktop.
Blur effect with given intensity
import UIKit
import SnapKit
extension UIView {
// MARK: Blur
func addBlur() {
backgroundColor = .clear
let blurView = makeBlurView()
insertSubview(blurView, at: 0)
blurView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
func makeBlurView(with intensity: CGFloat = 0.4) -> UIVisualEffectView {
let blurEffect = UIBlurEffect(style: .dark)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.setIntensity(intensity)
return blurView
}
}
}
import UIKit
extension UIVisualEffectView {
private var key: UnsafeRawPointer? { UnsafeRawPointer(bitPattern: 16) }
private var interface: VisualEffectViewInterface {
if let key = key, let visualEffectViewInterface = objc_getAssociatedObject(self, key) as? VisualEffectViewInterface {
return visualEffectViewInterface
}
let visualEffectViewInterface = VisualEffectViewInterface()
if let key = key {
objc_setAssociatedObject(self, key, visualEffectViewInterface, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
return visualEffectViewInterface
}
func setIntensity(_ intensity: CGFloat) {
interface.setIntensity(effectView: self, intensity: intensity)
}
final private class VisualEffectViewInterface {
private var animator: UIViewPropertyAnimator!
func setIntensity(effectView: UIVisualEffectView, intensity: CGFloat) {
let effect = effectView.effect
effectView.effect = nil
animator = UIViewPropertyAnimator(duration: 1, curve: .linear) { [weak effectView] in effectView?.effect = effect }
animator.fractionComplete = intensity
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment