Visual Effects Blur in SwiftUI
Nafeez Ahmed
Posted on January 2, 2023
Swift provides with different ways of displaying visual effects like blur and vibrancy effects. These can mostly be used as background for views and can be used to improve the overall app design. You can observe these blur effects throughout iOS like in app library, control center and app dock.
Materials
Adding visual effect as background in iOS 15 is as easy as doing the following:
Text("Hello, World!")
.frame(width: 200, height: 50)
.background(.thickMaterial)
Note:
If you are using any frame in your view, use the .background after that so that the background effect is applied for the required frame size.
This visual effect is actually an enum called Material which has thin, thick and regular properties.
Visual Effect using UIViewRepresentable
Above was the case for iOS 15+ only. But for >iOS15, you can use a mini UIViewRepresentable to implement visual effect into your app.
struct VisualEffect: UIViewRepresentable {
@State var style : UIBlurEffect.Style // 1
func makeUIView(context: Context) -> UIVisualEffectView {
return UIVisualEffectView(effect: UIBlurEffect(style: style)) // 2
}
func updateUIView(_ uiView: UIVisualEffectView, context: Context) {
} // 3
}
Code Explanation:
- Defining the state variable to take in the blur effect enum as a parameter.
- Returning a UIVisualEffectView (UIKit element) with the style variable.
- Since no view updates are required, no code is added to updateUIView.
Usage:
Text("Hello, World!”)
.frame(width: 150, height: 50, alignment: .center)
.background(VisualEffect(style: .systemThickMaterial))
There can be cases where on adding the blur effect to the view, the visual effect can look no different than a solid background color. In that case, you just need to play around with the alpha and opacity value of the visual effect.
Text("Hello, World!")
.frame(width: 150, height: 50, alignment: .center)
.background(.thin)
.background(
VisualEffect(style: .systemThickMaterial)
.opacity(0.8)
)
If you are looking forward to implement vibrancy effects like before, SwiftUI doesn't support the vibrancy effect natively. For that, you could go for Swift Packages like SwiftUI Visual Effects by Lucas Brown.
Wrapping up the article, today you learned about implementatoin of visuals effects in SwiftUI by using Material and about integrating the UIKit version. We encourage you to go over the concept of Colors & gradient in SwiftUI . Till then,
Eat. Sleep. Swift Anytime. Repeat.
Posted on January 2, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024