A masked view is view which only displays the pixels that overlap with the view rendered in its mask element. This can be incredibly powerful in creating complex UI elements, and it is a handy tool in animation.
In this video we will use a masked view to render text with unusual colours.
Masked View Expo | Pure React Native
Instructor: [0:00] Here we have a plain React Native project to render some text saying, "Hello world," and a view with three views inside it, a pink one, a purple one, and a teal one.
[0:15] Let's use a MaskedView to project these colors onto the text. We're going to use a library called React Native MaskedView. This can be used on Expo or on plain React Native.
[0:27] The API's identical, but the installation instructions are slightly different. If you're using Expo, you'll need to install it using Expo install.
[0:36] My project is using plain React Native, so I'm going to copy this yarn command, paste it into my terminal.
[0:43] Now because this is using native dependencies, I'm going to CD into the iOS directory and run pod install to install the iOS dependencies.
[0:53] Now CD back into the root directory and run NPX, React Native run iOS to rebuild the project.
[1:01] Now, after the project has been rebuilt, let's import MaskedView from React Native MaskedView. Let's render a MaskedView. Let's do a MaskedView.
[1:13] Now, as the content of the MaskedView let's pass in the colorful boxes that we have. I'm going to copy this from above and paste it inside the MaskedView component. As the mask element prop, this is the component that all the content will get projected onto, we will copy the "Hello world" text.
[1:36] Let's Copy and Paste it here and Save. Now after rerendering, we will see that the background is now projected onto the "Hello world" text. This can be powerful because we can literally put anything here as the content and it will get projected onto the masked element.
[1:54] For example, I can take this lovely sunny image. I'm going to assign this to a constant. Const imageURI = thisURL. I'm going to import image from React Native.
[2:10] I'm going to comment out the content that we had here before and instead render an image with sourceURI being the image URI and style = styles.image. We'll have to create an image style for the width and height. Let's do image and let's do a height of 100 and a width of 300.
[2:40] Saving this, you'll see that the blue sky is now visible through the text of our mask element.