Set a shape as background in SwiftUI
SwiftUI provides a simple way to set a view's background to a shape, like a capsule or rounded rectangle, using the background(_:in:fillStyle:) modifier. This avoids the need to clip the background or separately define and fill a shape.
Here's an example:
Text("Hello, world!")
.font(.title)
.fontWeight(.semibold)
.padding(22)
.background(
Color.yellow.gradient,
in: Capsule()
)
In this case, the capsule filled with a subtle yellow gradient is layered behind the text using background(Color.yellow.gradient, in: Capsule())
.


This convenience method works with shapes that conform to the InsettableShape protocol, like Capsule
, Rectangle
, Circle
, and RoundedRectangle
.
If you want to build a strong foundation in SwiftUI, my new book SwiftUI Fundamentals takes a deep dive into the framework’s core principles and APIs to help you understand how it works under the hood and how to use it effectively in your projects.
For more resources on Swift and SwiftUI, check out my other books and book bundles.