如何将svg路径放入React Native中的svg视图框中



我正在尝试实现条形码扫描仪viewFinder,我想使用svg图标使其看起来很漂亮,但我在强制svg内部的路径元素占据整个svg宽度和高度方面遇到了问题。我使用的是react native,为了生成图标,我使用SVGRhttps://react-svgr.com/playground/?native=true&typescript=true在扫描处理程序中,我设置svg的维度,如下所示:

const handleBarCodeScanned = ({ type, data, bounds }: BarCodeEvent) => {
if (!bounds) return;
const { origin, size } = bounds;
setX(origin.x);
setY(origin.y);
setWidth(size.width);
setHeight(size.height);
};

我把它们放在svg里,看起来像

import * as React from "react";
import Svg, { SvgProps, Path } from "react-native-svg";
export const ViewFinder = (props: SvgProps & { top: number; left: number }) => {
const { width, height, top, left } = props;
return (
<Svg
width={width}
height={height}
style={{
borderColor: "green",
borderWidth: 2,
position: "absolute",
left: 0,
top: 0,
width: "100%",
height: "100%",
}}
fill="none"
stroke="green"
preserveAspectRatio="none"
viewBox={`0 0 ${width} ${height}`}
>
<Path d="M6.13 1L6 16a2 2 0 0 0 2 2h15"></Path>
<Path d="M1 6.13L16 6a2 2 0 0 1 2 2v15"></Path>
</Svg>
);
};

原始图标是featerIcons裁剪图标https://feathericons.com/图标的原始代码为:

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-crop"><path d="M6.13 1L6 16a2 2 0 0 0 2 2h15"></path><path d="M1 6.13L16 6a2 2 0 0 1 2 2v15"></path></svg>

正如你所看到的,我在svg本身上设置了边框颜色和borderWidth,它可以根据容器进行缩放,所以这里一切似乎都很好。

非常感谢你的帮助。

通常,viewBox是4个固定数字,即与宽度和高度无关。这应该会给你想要的结果。

您的内容大小不变,因此您的viewBox也不应更改。

最新更新