Search code examples
javascriptreactjsreact-nativeimage-masking

React Native - add a masked circle overlay over image


How do I go about adding an opaque circular overlay over an image in React Native? Similar to the instagram image picker:

enter image description here

as trivial a task this may seem, I've had a world of trouble replicating this. Any suggestions?


Solution

  • As someone mentioned in the comments, the way to achieve this is with React Native Masked View.

    Install it in your project by running:

    npm install -S @react-native-community/masked-view
    

    or

    yarn add @react-native-community/masked-view
    

    Then you can use it as follows. I've adapted the example from their README for you here:

    import MaskedView from '@react-native-community/masked-view';
    import React from 'react';
    import { View } from 'react-native';
    
    export default class App extends React.Component {
      render() {
        return (
          <View
            style={{
              flex: 1,
              backgroundColor: '#000000', // "Edge" background
              maxHeight: 400,
            }}
          >
            <MaskedView
              style={{ flex: 1 }}
              maskElement={
                <View
                  style={{
                    // Transparent background mask
                    backgroundColor: '#00000077', // The '77' here sets the alpha
                    flex: 1,
                  }}
                >
                  <View
                    style={{
                      // Solid background as the aperture of the lens-eye.
                      backgroundColor: '#ff00ff',
                      // If you have a set height or width, set this to half
                      borderRadius: 200,
                      flex: 1,
                    }}
                  />
                </View>
              }
            >
              {/* Shows behind the mask, you can put anything here, such as an image */}
              <View style={{ flex: 1, height: '100%', backgroundColor: '#324376' }} />
              <View style={{ flex: 1, height: '100%', backgroundColor: '#F5DD90' }} />
              <View style={{ flex: 1, height: '100%', backgroundColor: '#F76C5E' }} />
              <View style={{ flex: 1, height: '100%', backgroundColor: '#2E6D3E' }} />
            </MaskedView>
          </View>
        );
      }
    }