UIVisualEffect
There are only two kinds of UIVisualEffect- Blur, and Vibrancy. blur view is applied to, revealing the content underneath. A blur effect can be Extra Light, Light, or Dark. Vibrancy effects depend on the blur effect of the view they are added to. They are used to dynamically adjust the contrast of labels and icons, positioned on top of a blurred view, making them look sharper.
We use these effects by initializing a visual effect view and passing the effect as a parameter. UIVisualEffectView is a subclass of UIView, but in order for everything to work as expected, you should add subviews to its contentView.We can achieve this by using interface builder and also programmatically.
Step 1
Open Xcode and create a new project of single view application.
Step 2
Drag an image view on the storyboard.
Blur View:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import UIKit class ViewController: UIViewController { @IBOutlet weak var imageview: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let blureffect = UIBlurEffect(style: .light) let blurredEffectView = UIVisualEffectView(effect: blureffect) blurredEffectView.frame = imageview.bounds view.addSubview(blurredEffectView) } } |
After that run code, we will get the visual effect on the image.
lets you add a “vibrancy” effect to your views – this is a translucency effect designed to ensure that text is readable when it’s over any kind of blurred background, and it’s used to create that soft glow effect you see in the notification center.
We could extend the previous example so that it adds a segmented control in the middle of the view, using a vibrancy effect.
This is accomplished by creating a second UIVisualEffectView inside the first one, this time using UIVibrancyEffect to create the glow.
Note that you need to use the same blur type for both your visual effect views, otherwise the glow effect will be incorrect.
Vibrancy view:
Now, let’s add a text label with a vibrancy effect.
1 2 3 4 5 6 7 8 9 |
let vibrancyView: UIVisualEffectView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect)) vibrancyView.frame = imageview.bounds blurredEffectView.contentView.addSubview(vibrancyView) var label: UILabel = UILabel() label.frame = imageview.bounds label.text = "Hello world" label.textAlignment = .center label.textColor = UIColor.white vibrancyView.contentView.addSubview(label) |
Now, run the app.
What if the user has blur disabled?
In the simulator or on your device, open the Settings app and go to Accessibility ▸ Display & Text Size, and enable Reduce Transparency.
1 2 3 |
guard !UIAccessibility.isReduceTransparencyEnabled else { return } |
This code checks to see if Reduce Transparency is on. If it is, ignore all the code you just wrote and go back to the original layout without any blurring.
For other blogs Please click here