Discover how to create a background blur effect and give more importance to your text in SwiftUI using the new materials.

Sometimes we need to add text on top of an image and, to make it stand out, it is useful to add a background that is in harmony with the image underneath.

Luckily, this task is made significantly simple with SwiftUI and can be achieved with the use of materials.

Screenshot-2023-11-29-at-11.38.24-2.webp

A material is not a view, is like inserting a translucent layer between the modified view and its background.

The blurring effect produced by the material isn’t simple transparency. It uses a platform-specific blending that produces a result that resembles frosted glass.

Materials

SwiftUI has a set of materials with different thicknesses. Thicker materials give better contrast for text and other views.

Materials available in SwiftUI are:

  • regular material
  • thin material
  • ultra-thin material
  • thick material
  • ultra-thick material
  • bar

Usage

To apply a material to a view background, you need to use the background(_:ignoresSafeAreaEdges:) modifier.

Text("Ultra thin material")

.background(.ultraThinMaterial)

Shaped material

To shape the background material you can use the background(_:in:fillStyle:) modifier.

Passing a Shape object to the second parameter of the modifier.

Text("Ultra thin material")

.background(

.ultraThinMaterial,

in: RoundedRectangle(cornerRadius: 8, style: .continuous)

)

Dark mode

These materials automatically support both the light and dark modes.

Here is a list of all the available materials in SwiftUI.

Screenshot-2023-11-29-at-09.43.21.webp

If you have any question about this article, feel free to email me or tweet me @franceleonidev and share your opinion.

Thank you for reading and see you in the next article!

Source link