Skip to content
Advertisement

How to fit svg path into svg viewbox in React Native

I am trying to implement barcode scanner viewFinder and I want to use svg icon to make it look nice, but I have a problem with forcing the path element inside the svg to take up the full svg width and height. I am using react native and to generate icon i use SVGR https://react-svgr.com/playground/?native=true&typescript=true in the scan handler I set the dimensions of the svg like so:

  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);
  };

and the I ise them inside the svg which looks like so

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>
  );
};

original icon is a featerIcons crop icon https://feathericons.com/ and the original code of the icon is:

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

as you can see I set the border color and borderWidth on the svg itself, and it scales to fit the container so here everything seems to be ok. I have viewBox and preserveAspectRatio set up its just the inner path not scaling with the svg, and it is not just this icon I have tries several and the issue is still this same so there must be something wrong with my understanding of svg.

Thanks a lot for any help.

Advertisement

Answer

Normally a viewBox would be 4 fixed numbers, i.e. unrelated to width and height. That should give you the result you want.

Your content doesn’t change in size so your viewBox shouldn’t change either.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement