我想把一个
react-native-svg
元素放在一个View
里,以一定的比例渲染出来,然后尽量缩放到最大,但限制在包含视图的范围内。
Svg
元素(来自react-native-svg
)似乎只接受绝对的width
和height
属性(我尝试过使用百分比,但什么都没有渲染出来,并且调试证实百分比值在传递到本地视图时为NSNull
)。我不确定如何实现所需的效果。这是我迄今为止尝试过的:// I have a component defined like this:
export default class MySvgCircle extends React.Component {
render() {
return (
<View style={[this.props.style, {alignItems: 'center', justifyContent: 'center'}]} ref="containingView">
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center', aspectRatio: 1.0}}>
<Svg.Svg width="100" height="100">
<Svg.Circle cx="50" cy="50" r="40" stroke="blue" strokeWidth="1.0" fill="transparent" />
<Svg.Circle cx="50" cy="50" r="37" stroke="red" strokeWidth="6.0" fill="transparent" />
</Svg.Svg>
</View>
</View>
);
}
}
// And then consumed like this:
<MySvgCircle style={{height: 200, width: 200, backgroundColor: "powderblue"}}/>
这是渲染后我所看到的内容。
我希望红色和蓝色圆圈能够被缩放以填满200x200的区域(如果包含视图不是正方形而是矩形,则保持圆形),而不需要预先知道组件的使用者希望的尺寸。
如前所述,我试过使用百分比,像这样(其余部分相同):
<Svg.Svg width="100%" height="100%">
但是SVG部分根本没有绘制。像这样:
在控制台日志中没有错误消息或其他指示说明为什么不起作用。
RN中测量UI元素布局后的方法似乎是异步的,这似乎与我要做的事情不太匹配。是否有一些缩放或变换魔术可以使用?
所需的输出应如下所示(通过硬编码值获得):
当包含视图不是完美正方形时,我希望它像这样工作: