Skip to content

Commit

Permalink
SVG: Added support for RGBA, HSL and HSLA colours
Browse files Browse the repository at this point in the history
  • Loading branch information
ed95 committed Apr 24, 2020
1 parent 6cb75d9 commit 49361b4
Showing 1 changed file with 47 additions and 22 deletions.
69 changes: 47 additions & 22 deletions modules/juce_gui_basics/drawables/juce_SVGParser.cpp
Expand Up @@ -1518,16 +1518,18 @@ class SVGState

if (text.startsWithChar ('#'))
{
uint32 hex[6] = { 0 };
uint32 hex[8] = { 0 };
hex[6] = hex[7] = 15;

int numChars = 0;
auto s = text.getCharPointer();

while (numChars < 6)
while (numChars < 8)
{
auto hexValue = CharacterFunctions::getHexDigitValue (*++s);

if (hexValue >= 0)
hex [numChars++] = (uint32) hexValue;
hex[numChars++] = (uint32) hexValue;
else
break;
}
Expand All @@ -1539,30 +1541,53 @@ class SVGState

return Colour ((uint8) ((hex[0] << 4) + hex[1]),
(uint8) ((hex[2] << 4) + hex[3]),
(uint8) ((hex[4] << 4) + hex[5]));
(uint8) ((hex[4] << 4) + hex[5]),
(uint8) ((hex[6] << 4) + hex[7]));
}

if (text.startsWith ("rgb"))
if (text.startsWith ("rgb") || text.startsWith ("hsl"))
{
auto openBracket = text.indexOfChar ('(');
auto closeBracket = text.indexOfChar (openBracket, ')');
auto tokens = [&text]
{
auto openBracket = text.indexOfChar ('(');
auto closeBracket = text.indexOfChar (openBracket, ')');

StringArray arr;

if (openBracket >= 3 && closeBracket > openBracket)
{
arr.addTokens (text.substring (openBracket + 1, closeBracket), ",", "");
arr.trim();
arr.removeEmptyStrings();
}

if (openBracket >= 3 && closeBracket > openBracket)
return arr;
}();

auto alpha = [&tokens, &text]
{
StringArray tokens;
tokens.addTokens (text.substring (openBracket + 1, closeBracket), ",", "");
tokens.trim();
tokens.removeEmptyStrings();

if (tokens[0].containsChar ('%'))
return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
(uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
(uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));

return Colour ((uint8) tokens[0].getIntValue(),
(uint8) tokens[1].getIntValue(),
(uint8) tokens[2].getIntValue());
}
if ((text.startsWith ("rgba") || text.startsWith ("hsla")) && tokens.size() == 4)
return tokens[3].getFloatValue();

return 1.0f;
}();

if (text.startsWith ("hsl"))
return Colour ((float) (tokens[0].getDoubleValue() / 360.0),
(float) (tokens[1].getDoubleValue() / 100.0),
(float) (tokens[2].getDoubleValue() / 100.0),
alpha);

if (tokens[0].containsChar ('%'))
return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
(uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
(uint8) roundToInt (2.55 * tokens[2].getDoubleValue()),
alpha);

return Colour ((uint8) tokens[0].getIntValue(),
(uint8) tokens[1].getIntValue(),
(uint8) tokens[2].getIntValue(),
alpha);
}

if (text == "inherit")
Expand Down

0 comments on commit 49361b4

Please sign in to comment.