react-native-masked-view / masked-view

React Native Masked View Library
MIT License
960 stars 120 forks source link

[SOLVED] Creating a masked out camera view + conceptual explanation how masking works. #219

Closed samsnori closed 6 months ago

samsnori commented 6 months ago

image

  /*
   To grasp how the `MaskedView` operates, imagine it this way:
    the `MaskedView` generates an alpha layer and applies it to
    its children. The outcome is then displayed on top of the
    background, as is typically done.

    In this instance, the `maskElement` generates an alpha layer
    with a transparency of 0.3 everywhere, except for the
    `<View>` element with the `css_cutout` style. There, the
    alpha values are set to 1.0, indicating that no transparency
    blending will occur.

        ┌─────────────────────────┐   
        │ 0.3, 0.3, 0.3, 0.3, 0.3 │   
        │                         │   
        │ 0.3, 0.3, 0.3, 0.3, 0.3 │   
        │                         │   
        │ 0.3, 0.3, 0.3, 0.3, 0.3 │   
        │                         │   
        │ 0.3, 0.3, 0.3, 0.3, 0.3 │   
        │     ┌─────────────┐     │   
        │ 0.3 │1.0, 1.0, 1.0│ 0.3 │   
        │     │             │     │   
        │ 0.3 │1.0, 1.0, 1.0│ 0.3 │   
        │     │             │     │   
        │ 0.3 │1.0, 1.0, 1.0│ 0.3 │   
        │     └─────────────┘     │   
        │ 0.3, 0.3, 0.3, 0.3, 0.3 │   
        │                         │   
        │ 0.3, 0.3, 0.3, 0.3, 0.3 │   
        │                         │   
        │ 0.3, 0.3, 0.3, 0.3, 0.3 │   
        │                         │   
        │ 0.3, 0.3, 0.3, 0.3, 0.3 │   
        └─────────────────────────┘   

   In this case the "backdrop" view is black which blends with
   the result of the masked view make those pixels a bit darker.

   */
  let css_wrapper = {
    ...StyleSheet.absoluteFill,
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
    justifyContent: 'center',
    alignItems: 'center'
  };

  let css_cutout = {
    width: 200,
    height: 200,
    backgroundColor: 'rgba(0, 0, 0, 1.0)'
  };

  let css_backdrop = {
    flex: 1,
    backgroundColor: 'black',
  };

  return (
    <View style={css_backdrop}>
      <MaskedView
        style={{flex: 1}}
        maskElement={
          <View style={css_wrapper}>
            <View style={css_cutout} />
          </View>
        }
      >
        <ImageBackground source={require('@app/assets/img/bg-test.png')} style={{flex: 1}}>
        </ImageBackground>
      </MaskedView>
    </View>
  );