2016-10-24 10 views
0

指定されたサイズのカラーサークルを描画するコンポーネントを作成しました。円の中心には数や文字が表示されます。ReactNative:サークルビューの境界線の上にビューを配置

enter image description here

また、緑の円が円の境界に右下の隅に表示されなければなりません。

ReactNative-スタイルシートは次のように見える:

circle: { 
    width: 100, // this should be a "props"-value in future 
    height: 100, // this should be a "props"-value in future 
    borderRadius: 100/2, 
    backgroundColor: 'red', 
    alignItems: 'center', 
    justifyContent: 'center', 
    }, 

    circleCaption: { 
    fontSize: 70, 
    }, 

    symbol: { 
    width: 16, 
    height: 16, 
    borderRadius: 16/2, 
    backgroundColor: 'green', 
    position: 'absolute', 
    right: 8, 
    bottom: 8, 
    }, 

および形状がビューにこのように配置されている:

<View style={s.circle}> 
     <Text style={s.circleCaption}>A</Text> 
     <View style={s.symbol} /> 
    </View> 

これらの要因により(右:8、底:8)、緑色の円は円の右下隅に直接配置されます。

サークルサイズで動的に配置するにはどうすればよいですか?ボトム/右側の値はどのようにして計算できますか?

また、赤い円の中心に描かれた文字、数字または記号が大きすぎて円に収まらない場合、緑の円は円から離れて固定位置を失います。についての任意のアイデア?残念ながら、ReactNativeが提供するZ-Indexはありません。

答えて

4

それを行う方法が円上の点の位置を計算するための式を使用することです:

x = r * cos(a) + cx 
y = r * sin(a) + cy 

xy - 私たちは

を見つけたい点位置r - 円の半径

a - 角度(ここでは45度を必要とする)

cxcy - JS Math.cosおよびMath.sin引数としてラジアン単位の角度を取るので、我々はラジアン度から45角度を変換する必要があることを円中心点位置

注意。

function degToRad(deg) { 
    return deg * Math.PI/180; 
} 

すべてのダイナミックなスタイルはコンポーネント内に移動されてきたが、ここでは左です:

const s = StyleSheet.create({ 
    circle: { 
    backgroundColor: 'red', 
    alignItems: 'center', 
    justifyContent: 'center', 
    }, 
    circleCaption: { 
    fontSize: 70, 
    }, 
    symbol: { 
    backgroundColor: 'green', 
    position: 'absolute', 
    }, 
}); 

とコンポーネント自体:

export default function Circle(props) { 
    const { size, symbolSize } = props; 

    const angleRad = degToRad(45); 
    const radius = size/2; 
    const center = radius; 

    // Calculate symbol position 
    // Subtract half of symbol size to center it on the circle 
    const x = radius * Math.cos(angleRad) + center - symbolSize/2; 
    const y = radius * Math.sin(angleRad) + center - symbolSize/2; 

    return (
    <View 
     style={[s.circle, { 
     width: size, 
     height: size, 
     borderRadius: size/2, 
     }]} 
    > 
     <Text style={s.circleCaption}>A</Text> 
     <View 
     style={[ 
      s.symbol, { 
      width: symbolSize, 
      height: symbolSize, 
      borderRadius: symbolSize/2, 
      left: x, 
      top: y, 
     }]} 
     /> 
    </View> 
); 
} 

使用例:

<Circle 
    size={100} 
    symbolSize={16} 
/> 
+0

コードスニペットをありがとう、それは私を助けたロット! –

関連する問題