Twitter LogoFacebook Logo
Mask
Hello, in this tutorial, I will show you how to use the Mask modifier from SwiftUI to hide part of your views.
By: King

The Mask modifier in SwiftUI is used to hide part of your view. It takes the invisible portion of one view and apply it to another.

Image from Codeible.com

To begin, create a new SwiftUI project. 

In the ContentView, apply the frame() modifier on the Text view and set the maxWidth and maxHeight to .infinity

This will make the Text fill up the whole screen.

Then apply the background() modifier and change its color to red.

To apply a mask, open the XCode library and search for Mask in the modifier menu. 

Image from Codeible.com

Drag and drop it at the end of the view you want to mask.

It takes in a view that you want to use to apply its alpha content. This can be an image with alpha channels such as a PNG file or it can be one of the built-in shapes in SwiftUI.

Using an Image

To use an image, locate a PNG file on your computer and drag it into the “Assets” folder. 


Then inside the mask() modifier, add an Image view and put the name of the image you just added to the project.

Image from Codeible.com

If we look at the preview, the invisible portion of the image is applied to the Text view.

Image from Codeible.com

Using Built-in Shapes

Some common shapes in SwiftUI is the 


Rectangle
RoundedRectangle
Capsule
Ellipse
Circle

To apply these shapes as the mask exactly the same as how we used the Image view.

Remove the Image view from the mask modifier then add a shape inside the parenthesis.

Image from Codeible.com

Sign In