Skip to content

Commit

Permalink
MaskedViewIOS -- A way to apply alpha masks to views on iOS
Browse files Browse the repository at this point in the history
Summary:
It's very important in complex UIs to be able to apply alpha channel-based masks to arbitrary content. Common use cases include adding gradient masks at the top or bottom of scroll views, creating masked text effects, feathering images, and generally just masking views while still allowing transparency of those views.

The original motivation for creating this component stemmed from work on `react-navigation`. As I tried to mimic behavior in the native iOS header, I needed to be able to achieve the effect pictured here (this is a screenshot from a native iOS application):

![iOS native navbar animation](https://slack-imgs.com/?c=1&url=https%3A%2F%2Fd3vv6lp55qjaqc.cloudfront.net%2Fitems%2F0N3g1Q3H423P3m1c1z3E%2FScreen%2520Shot%25202017-07-06%2520at%252011.57.29%2520AM.png)

In this image, there are two masks:

- A mask on the back button chevron
- A gradient mask on the right button

In addition, the underlying view in the navigation bar is intended to be a UIBlurView. Thus, alpha masking is the only way to achieve this effect.

Behind the scenes, the `maskView` property on `UIView` is used. This is a shortcut to setting the mask on the CALayer directly.

This gives us the ability to mask any view with any other view. While building this component (and testing in the context of an Expo app), I was able to use a `GLView` (a view that renders an OpenGL context) to mask a `Video` component!

I chose to implement this only on iOS right now, as the Android implementation is a) significantly more complicated and b) will most likely not be as performant (especially when trying to mask more complex views).

Review the `<MaskedViewIOS>` section in the RNTester app, observe that views are masked appropriately.

![example](https://d3vv6lp55qjaqc.cloudfront.net/items/250X092v2k3f212f3O16/Screen%20Recording%202017-07-07%20at%2012.18%20PM.gif?X-CloudApp-Visitor-Id=abb33b3e3769bbe2f7b26d13dc5d1442&v=5f9e2d4c)
Closes #14898

Differential Revision: D5398721

Pulled By: javache

fbshipit-source-id: 343af874e2d664541aca1fefe922cf7d82aea701
  • Loading branch information
Adam Miskiewicz authored and facebook-github-bot committed Jul 11, 2017
1 parent 0c44b9e commit 8ea6cea
Show file tree
Hide file tree
Showing 12 changed files with 441 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Libraries/Components/MaskedView/MaskedViewIOS.android.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule MaskedViewIOS
* @flow
*/
'use strict';

module.exports = require('UnimplementedView');
110 changes: 110 additions & 0 deletions Libraries/Components/MaskedView/MaskedViewIOS.ios.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule MaskedViewIOS
* @flow
*/

const React = require('React');
const StyleSheet = require('StyleSheet');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
const requireNativeComponent = require('requireNativeComponent');
const ReactPropTypes = React.PropTypes;

import type { ViewProps } from 'ViewPropTypes';

type Props = ViewProps & {
children: any,
/**
* Should be a React element to be rendered and applied as the
* mask for the child element.
*/
maskElement: React.Element<*>,
};

/**
* Renders the child view with a mask specified in the `maskElement` prop.
*
* ```
* import React from 'react';
* import { MaskedView, Text, View } from 'react-native';
*
* class MyMaskedView extends React.Component {
* render() {
* return (
* <MaskedView
* style={{ flex: 1 }}
* maskElement={
* <View style={styles.maskContainerStyle}>
* <Text style={styles.maskTextStyle}>
* Basic Mask
* </Text>
* </View>
* }
* >
* <View style={{ flex: 1, backgroundColor: 'blue' }} />
* </MaskedView>
* );
* }
* }
* ```
*
* The above example will render a view with a blue background that fills its
* parent, and then mask that view with text that says "Basic Mask".
*
* The alpha channel of the view rendered by the `maskElement` prop determines how
* much of the view's content and background shows through. Fully or partially
* opaque pixels allow the underlying content to show through but fully
* transparent pixels block that content.
*
*/
class MaskedViewIOS extends React.Component {
props: Props;

static propTypes = {
...ViewPropTypes,
maskElement: ReactPropTypes.element.isRequired,
};

_hasWarnedInvalidRenderMask = false;

render() {
const { maskElement, children, ...otherViewProps } = this.props;

if (!React.isValidElement(maskElement)) {
if (!this._hasWarnedInvalidRenderMask) {
console.warn(
'MaskedView: Invalid `maskElement` prop was passed to MaskedView. ' +
'Expected a React Element. No mask will render.'
);
this._hasWarnedInvalidRenderMask = true;
}
return <View {...otherViewProps}>{children}</View>;
}

return (
<RCTMaskedView {...otherViewProps}>
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
{maskElement}
</View>
{children}
</RCTMaskedView>
);
}
}

const RCTMaskedView = requireNativeComponent('RCTMaskedView', {
name: 'RCTMaskedView',
displayName: 'RCTMaskedView',
propTypes: {
...ViewPropTypes,
},
});

module.exports = MaskedViewIOS;
1 change: 1 addition & 0 deletions Libraries/react-native/react-native-implementation.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const ReactNative = {
get ImageStore() { return require('ImageStore'); },
get KeyboardAvoidingView() { return require('KeyboardAvoidingView'); },
get ListView() { return require('ListView'); },
get MaskedViewIOS() { return require('MaskedViewIOS'); },
get Modal() { return require('Modal'); },
get NavigatorIOS() { return require('NavigatorIOS'); },
get Picker() { return require('Picker'); },
Expand Down
196 changes: 196 additions & 0 deletions RNTester/js/MaskedViewExample.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @providesModule MaskedViewExample
*/
'use strict';

const React = require('react');
const RNTesterBlock = require('RNTesterBlock');
const RNTesterPage = require('RNTesterPage');
const {
Animated,
Image,
MaskedViewIOS,
StyleSheet,
Text,
View,
} = require('react-native');

class MaskedViewExample extends React.Component {
static title = '<MaskedViewIOS>';
static description = 'Renders the child view with a mask specified in the `renderMask` prop.';

state = {
alternateChildren: true,
};

_maskRotateAnimatedValue = new Animated.Value(0);
_maskScaleAnimatedValue = new Animated.Value(1);

componentDidMount() {
setInterval(() => {
this.setState(state => ({
alternateChildren: !state.alternateChildren,
}));
}, 1000);

Animated.loop(
Animated.sequence([
Animated.timing(this._maskScaleAnimatedValue, {
toValue: 1.3,
timing: 750,
useNativeDriver: true,
}),
Animated.timing(this._maskScaleAnimatedValue, {
toValue: 1,
timing: 750,
useNativeDriver: true,
}),
])
).start();

Animated.loop(
Animated.timing(this._maskRotateAnimatedValue, {
toValue: 360,
timing: 2000,
useNativeDriver: true,
})
).start();
}

render() {
return (
<RNTesterPage title="<MaskedViewIOS>">
<RNTesterBlock title="Basic Mask">
<View style={{ width: 300, height: 300, alignSelf: 'center' }}>
<MaskedViewIOS
style={{ flex: 1 }}
maskElement={
<View style={styles.maskContainerStyle}>
<Text style={styles.maskTextStyle}>
Basic Mask
</Text>
</View>
}>
<View style={{ flex: 1, backgroundColor: 'blue' }} />
<View style={{ flex: 1, backgroundColor: 'red' }} />
</MaskedViewIOS>
</View>
</RNTesterBlock>
<RNTesterBlock title="Image Mask">
<View
style={{
width: 300,
height: 300,
alignSelf: 'center',
backgroundColor: '#eeeeee',
}}>
<MaskedViewIOS
style={{ flex: 1 }}
maskElement={
<View style={styles.maskContainerStyle}>
<Image
style={{ height: 200, width: 200 }}
source={require('./imageMask.png')}
/>
</View>
}>
<View style={styles.maskContainerStyle}>
<Image
resizeMode="cover"
style={{ width: 200, height: 200 }}
source={{
uri:
'https://38.media.tumblr.com/9e9bd08c6e2d10561dd1fb4197df4c4e/tumblr_mfqekpMktw1rn90umo1_500.gif',
}}
/>
</View>
</MaskedViewIOS>
</View>
</RNTesterBlock>
<RNTesterBlock title="Animated Mask">
<View style={{ width: 300, height: 300, alignSelf: 'center' }}>
<MaskedViewIOS
style={{ flex: 1 }}
maskElement={
<Animated.View
style={[
styles.maskContainerStyle,
{ transform: [{ scale: this._maskScaleAnimatedValue }] },
]}>
<Text style={styles.maskTextStyle}>
Basic Mask
</Text>
</Animated.View>
}>
<Animated.View
style={{
flex: 1,
transform: [
{
rotate: this._maskRotateAnimatedValue.interpolate({
inputRange: [0, 360],
outputRange: ['0deg', '360deg'],
}),
},
],
}}>
<View style={{ flex: 1, backgroundColor: 'blue' }} />
<View style={{ flex: 1, backgroundColor: 'red' }} />
</Animated.View>
</MaskedViewIOS>
</View>
</RNTesterBlock>
<RNTesterBlock title="Mask w/ Changing Children">
<View style={{ width: 300, height: 300, alignSelf: 'center' }}>
<MaskedViewIOS
style={{ flex: 1 }}
maskElement={
<View style={styles.maskContainerStyle}>
<Text style={styles.maskTextStyle}>
Basic Mask
</Text>
</View>
}>
{this.state.alternateChildren
? [
<View
key={1}
style={{ flex: 1, backgroundColor: 'blue' }}
/>,
<View
key={2}
style={{ flex: 1, backgroundColor: 'red' }}
/>,
]
: null}
</MaskedViewIOS>
</View>
</RNTesterBlock>
</RNTesterPage>
);
}
}

const styles = StyleSheet.create({
maskContainerStyle: {
flex: 1,
backgroundColor: 'transparent',
justifyContent: 'center',
alignItems: 'center',
},
maskTextStyle: {
backgroundColor: 'transparent',
fontSize: 40,
fontWeight: 'bold',
},
});

module.exports = MaskedViewExample;
5 changes: 5 additions & 0 deletions RNTester/js/RNTesterList.ios.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ const ComponentExamples: Array<RNTesterExample> = [
module: require('./ListViewPagingExample'),
supportsTVOS: true,
},
{
key: 'MaskedViewExample',
module: require('./MaskedViewExample'),
supportsTVOS: true,
},
{
key: 'ModalExample',
module: require('./ModalExample'),
Expand Down
Binary file added RNTester/js/imageMask.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 8ea6cea

Please sign in to comment.