如何通过react native svg使文本居中于圆心?

时间:2019-09-19 14:26:30

标签: react-native react-native-svg

这很简单,但我有点迷茫。

如何使文字在圆的中间(垂直和水平)?或Svg中间的所有内容(然后文本将位于圆圈的中间)

const size = width < height ? width - 32 : height - 16
const strokeWidth = 25
const radius = (size - strokeWidth) / 2
const circunference = radius * 2 * Math.PI

return (
    <Svg width={width} height={size}>
        <Text>
            Hey
        </Text>
        <Circle
            stroke="#2162cc"
            fill="none"
            cx={size / 2}
            cy={size / 2}
            r={radius}
            strokeDasharray={`${circunference} ${circunference}`}
            {...{ strokeWidth, strokeDashoffset }}
        />
    </Svg>
)

2 个答案:

答案 0 :(得分:1)

您将必须使用Text中的react-native-svg组件,如下所示。希望这会有所帮助

import React, { Component } from "react";
import Svg, { Circle, Text } from "react-native-svg";

class Demo extends Component {
  render() {
    const width = 100;
    const height = 100;
    const size = width < height ? width - 32 : height - 16;
    const strokeWidth = 25;
    const radius = (size - strokeWidth) / 2;
    const circunference = radius * 2 * Math.PI;

    return (
      <Svg width={width} height={size}>
        <Text
          stroke="purple"
          fontSize="15"
          x={size / 2}
          y={size / 2}
          textAnchor="middle"
        >
          Hey
        </Text>
        <Circle
          stroke="#2162cc"
          fill="none"
          cx={size / 2}
          cy={size / 2}
          r={radius}
          strokeDasharray={`${circunference} ${circunference}`}
        />
      </Svg>
    );
  }
}

export default Demo;

答案 1 :(得分:0)

将顶部的SVG元素包装在View元素中,然后使用position absolute将圆定位为背景(如果不需要为该圆添加一些填充,请使用top: 3, left: 3添加“ padding”剪掉)。

在最外层的View元素上设置alignItems:'center', justifyContent: 'center',以使文本与视图的中心对齐。

示例

<View style={{alignItems: 'center', justifyContent: 'center'}}>
    <View style={{position: 'absolute'}}>
      <Svg width={width} height={size} >
          <Circle
              stroke="#2162cc"
              fill="none"
              cx={size / 2}
              cy={size / 2}
              r={radius}
              strokeDasharray={`${circunference} ${circunference}`}
              {...{ strokeWidth, strokeDashoffset }}
          />
      </Svg>
      <Text>
         Hey
      </Text>
   </View>
</View>

注意

此解决方案将适用于您要居中的任何类型的元素,无论多么复杂,而不仅仅是简单的文本。