首页 > 解决方案 > 在父容器中包含 React Native SVGText

问题描述

我正在使用 react-native-svg 包创建带有渐变的文本。我在文本上使用字体大小以及字体粗细。

我希望它尊重父容器的高度和宽度,并包含在父容器中而不从边缘切断,但不知何故它超出了界限。

这是我对该文本组件的实现:

import Svg, {
  Defs,
  RadialGradient,
  Stop,
  Text as SVGText,
  TSpan,
} from 'react-native-svg';
import React from 'react';
import { View } from 'react-native';
import { fonts } from '@curefit/uikit';

export type GradientTextProps = {
  text: string;
  fontSize: number;
  stopColorStart: string;
  stopColorEnd: string;
  subText?: string;
};

export const GradientText = (props: GradientTextProps) => {
  const { stopColorStart, stopColorEnd, fontSize } = props;
  return (
      <Svg width="100%" height="100%" preserveAspectRatio="xMidYMid meet">
        <Defs>
          <RadialGradient
            id="grad"
            cx="10"
            cy="75"
            rx="70"
            ry="70"
            fx="40"
            fy="75"
            gradientUnits="userSpaceOnUse"
          >
            <Stop offset="0" stopColor={stopColorStart} stopOpacity="1" />
            <Stop offset="1" stopColor={stopColorEnd} stopOpacity="1" />
          </RadialGradient>
        </Defs>
        {/*<Ellipse cx="20" cy="75" rx="45" ry="45" fill="url(#grad)" />*/}
        <SVGText
          fill="url(#grad)"
          fontFamily={fonts.Black}
          fontWeight={900}
          fontSize={72}
          textAnchor="middle"
        >
          <TSpan x="50%" y="75%">
            {props.text}
          </TSpan>
          {props?.subText ? (
            <TSpan x="50%" y="95%" fontSize={12}>
              {props.subText}
            </TSpan>
          ) : null}
        </SVGText>
      </Svg>
  );
};

我将 fontSize 传递为 72。父母的宽度为 80,高度为 72。在下面附上它的行为截图。

在此处输入图像描述

我在这里错过了什么吗?我尝试过设置viewBox="0 0 80 72",但效果不佳。

标签: androidiosreact-nativeradial-gradientsreact-native-svg

解决方案


推荐阅读