2

这个很简单,但我有点迷路了。

如何使文本位于圆圈的中间(垂直和水平)?或中间的所有内容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>
)
4

2 回答 2

5

您将不得不使用如下所示的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;

于 2019-09-19T14:51:01.117 回答
0

将顶部的 SVG 元素包裹在 View 元素中,然后使用绝对位置将圆圈定位为背景(top: 3, left: 3如果您需要一些填充以防止圆圈被剪切,请使用 '添加'填充')。

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

例子

<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>

笔记

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

于 2019-09-19T15:01:36.737 回答