PUROGU LADESU

ポエムがメインのブログです。

【ReactNative】ボックスに三角のラベルをつける

f:id:memorude:20200825231248p:plain

画像の上に三角形のラベルを表示

borderWidthで三角形の大きさを調整します。

<Image> ... </Image>
<View
  style={{
    position: 'absolute',
    left: 2,
    top: 2,
  }}
>
  <View
    style={{
      borderLeftColor: 'red',
      borderLeftWidth: 50,
      borderBottomColor: 'transparent',
      borderBottomWidth: 50,
    }}
  ></View>
  <Text
    style={{
      position: 'absolute',
      left: 2,
      top: 10,
      color: 'white',
      transform: [{ rotate: '-45deg' }],
      fontSize: 10,
      fontWeight: '600',
    }}
  >
    SOLD
  </Text>
</View>

iwb.jp

なぜborderWidthで三角形が表示されるのか

CSSのお話ですが、ボーダーを太くすると隣り合った辺は半分ずつ表示されるため、その性質を利用しているようです。 左のボーダーと下のボーダーなら左下から右上に向かって境界が描かれます。発見した人すごいですね。
下記のサンプルをやってみるとわかります。

<View
  style={{
    width: 100,
    height: 100,
    borderLeftColor: 'red',
    borderLeftWidth: 30,
    borderBottomColor: 'black',
    borderBottomWidth: 30,
    borderRightColor: 'blue',
    borderRightWidth: 30,
    borderTopColor: 'green',
    borderTopWidth: 30, 
  }}
></View>