SergeyMell / nativescript-plugins

Apache License 2.0
14 stars 4 forks source link

Change fill and stroke color #13

Open odedBartov opened 3 years ago

odedBartov commented 3 years ago

How can i change the color of the SVG image? It dosent matter what i put in this properties i still stuck with the default color

SergeyMell commented 3 years ago

You cannot do it through the properties (at least for now) as long as this functionality has not been implemented yet. However, you can

  1. Read the file sources
  2. Replace all needed colors according to your business logic
  3. Create and svg source using fromDatafunction like this
    private nsSvgData = `
        <svg ... </svg> // Here is your raw sources of the SVG that you've read from the file
    `;
    svgFile = fromData(this.nsSvgData);
  4. Render changed SVG like
    <SVGImage src="{{svgFile}}" width="335" height="269"><SVGImage>
SergeyMell commented 3 years ago

@odedBartov, was my answer helpful for you?

odedBartov commented 3 years ago

Not really, i want to change just one specific property (Color) of the image in the HTML, but thank you for the information

xiromoreira commented 2 years ago

If someone else ends here like me, trying to use files and not "inject" the svg in the code. Hope this saves someone's time or gives some ideas. After looking the source and understanding that won't be a trivial change to do I ended with this workaround based on your response.

Read the svg from assets folder:

  src = path.join(knownFolders.currentApp().path, 'assets', src);
  File.fromPath(src).readText().then(...)

Use a regex (:disappointed:) to replace or add the new attribute. It's not very restrictive, but I expect the base SVGs to be controlled and tested:

const REGEX_FILL = /<svg\s(([\s\w"=]*)(fill="#?\w+"))?/;
...
  svg.replace(REGEX_FILL, (...groups) => groups[2] != null
        ? `<svg ${groups[2]} fill="${fill}"`
        : `<svg fill="${attr}"`;
  );

And finally send the result to SVGImage src using the fromData() as suggested.