我已经构建了一个组件,它绘制了一个给定大小的彩色圆圈。在圆圈的中心显示一个数字或字符:
此外,应在圆圈边框的右下角显示绿色圆圈。
ReactNative-StyleSheet如下所示:
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。
答案 0 :(得分:5)
这样做的方法是使用公式计算圆上一个点的位置:
x = r * cos(a) + cx
y = r * sin(a) + cy
其中
x
和y
- 我们想要找到的点位置
r
- 圆的半径
a
- 角度(我们需要45度)
cx
和cy
- 圈子中心点位置
请注意,在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}
/>