Put a colour in a ValueTree

Hi quick question here that doesn’t seem to ba answered yet on the forum.

In order to let the user customise the look of a plug-in, I would like to hold a juce::Colour type inside a ValueTree object. So I need to make a var hold a Colour. Is there an easy way to do this ?

The solution I came up with is to store the colour as a string (ex : “0xff96bb7c”) and to create a new color every time it is needed. Even though it won’t really impact the speed of the plug-in in a noticeable way, I feel like this is highly inefficient. Another solution would be to implement a ReferenceCountedObject that only holds a colour, but this seems a “lot” of work for such a simple task.

Any ideas?

The question is, if the colour needs to be portable. If not you can use the underlying 32 bit integer.

But I went with the toString() approach, since it is portable and it is readable when I debug the contents of the ValueTree.

A word of warning about juce::Colour::fromString(): if you read HTML colours, it will shift the components, because it expects the alpha at the beginning and doesn’t complain if it got only 6 letters.

Here is my colour parser:

juce::Colour Stylesheet::parseColour (const juce::String& name)
    return juce::Colours::findColourForName (name, juce::Colour::fromString (name.length() < 8 ? "ff" + name : name));

The beauty is, it also allows you to use colour names…

1 Like

Alternatively, you could make your own VarientConverter to parse to and from a var. For example:

namespace juce
    struct VariantConverter<juce::Colour>
        static Colour fromVar (const var& v) { return ...; }
        static var toVar (const Colour& fontType) { return ...; }

auto colour = juce::Colours::blue;
auto asVar = juce::VariantConverter<juce::Colour>::toVar(colour);
auto asCol = juce::VariantConverter<juce::Colour>::fromVar(asVar);
jassert(colour == asCol);

This is better if you want to make sure you’re consistent throughout your codebase with how you’re converting to and from vars, and means if you want to change it up you need only do it in one place.


Damn this is nice, thank you so much!