Mask modifier in SwiftUI gives us ability to mask one view with another. Let’s start with a simple example.
We will create a Rectangle of size 200x200 and fill it with an orange color.
Rectangle()
.fill(Color.orange)
.frame(width: 200, height: 200)
We will add an overlay with DevTechie text view with large font:
Rectangle()
.fill(Color.orange)
.frame(width: 200, height: 200)
.overlay(Text("DevTechie").font(.largeTitle))
Next, we will mask this Rectangle to cut a shape of heart. We will do this by adding a mask modifier and for the content of mask, we will add a system image of heart:
Rectangle()
.fill(Color.orange)
.frame(width: 200, height: 200)
.overlay(Text("DevTechie").font(.largeTitle))
.mask {
Image(systemName: "heart.fill")
.resizable()
.frame(width: 200, height: 200)
}
And that’s how we mask with mask modifier 😅
With mask modifier we can create some really creative Text views.
For example, we can display a network image and mask it with DevTechie text as shown below:
struct MaskingExample: View {
var body: some View {
AsyncImage(url: URL(string: "https://images.unsplash.com/photo-1648650571468-501c7dad85f2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1287&q=80")!, scale: 1.0) { image in
image
.resizable()
.scaledToFit()
} placeholder: {
RoundedRectangle(cornerRadius: 10)
}.mask {
Text("DevTechie")
.font(.custom("Avnair", size: 64))
}
}
}
This will be our output:
With that we have reached the end of this article. Thank you once again for reading. Subscribe to our weekly newsletter at https://www.devtechie.com