Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature request] Color replacer #1060

Open
JCKodel opened this issue Apr 25, 2024 · 1 comment
Open

[Feature request] Color replacer #1060

JCKodel opened this issue Apr 25, 2024 · 1 comment

Comments

@JCKodel
Copy link

JCKodel commented Apr 25, 2024

Sometimes, we build apps where users can change the overall app color (especially when using Android, where it get the color theme from the current wall paper).

Now, imagine you have an SVG where only a part of it should follow the user's theme (an example of this is svgs from undrawn

undraw_undraw_undraw_undraw_love_it_xkc2_gyie_-1-ty26(1)_bkkj

It would be nice if we could replace one or more colors in our SVG before rendering, something like this:

SvgPicture.asset(
  "assets/some.svg",
  colorReplacer: {
    Color(0xff6c63ff): Color(0xffff0000),
    Colors.black: Colors.white,
  },
);

That would change color #6c63ff (that purple in the image) to #ff0000 (red) and all blacks to whites, just as an example, leaving the whites and beige (used in the skin) intact.

@gabrielginter
Copy link

This can be achieved by using the existing ColorMapper as follow:

SvgPicture(
  const SvgAssetLoader(
    'path/to/my/awesome.svg',
    colorMapper: SvgColorReplacer(
      colors: [ Color(0xff6c63ff) ,],
      replacements: [ Color(0xffff0000), ],
    ),
  ),
  fit: BoxFit.contain,
  width: [...],
  height: [...],
  [etc...]
);

class SvgColorReplacer implements ColorMapper {
  const SvgColorReplacer({
    required this.colors,
    required this.replacements,
  });

  final List<Color> colors;
  final List<Color> replacements;

  @override
  Color substitute(String? id, String elementName, String attributeName, Color color) {
    final colorIdx = colors.indexOf(color);
    if (colorIdx >= 0) return replacements[colorIdx];

    return color;
  }
}

You can adapt the code to use Map<Color, Color>. I used two lists to allow a const constructor.

Hope it helps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants