Skip to content

Commit

Permalink
Add support for rgb/rgba colors with percentages
Browse files Browse the repository at this point in the history
See #11 for details.
  • Loading branch information
meyfa committed Nov 13, 2016
1 parent 8c9e9d3 commit 81136fa
Showing 1 changed file with 28 additions and 10 deletions.
38 changes: 28 additions & 10 deletions src/SVG.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ final class SVG
/** @var string COLOR_HEX_3 A RegEx for #FFF etc */
const COLOR_HEX_3 = '/^#([0-9A-F])([0-9A-F])([0-9A-F])$/i';

/** @var string COLOR_RGB A RegEx for rgb(255, 255, 255) etc */
const COLOR_RGB = '/^rgb\(([+-]?\d*\.?\d*)\s*,\s*([+-]?\d*\.?\d*)\s*,\s*([+-]?\d*\.?\d*)\)$/';
/** @var string COLOR_RGBA A RegEx for rgba(255, 255, 255, 0.5) etc */
const COLOR_RGBA = '/^rgba\(([+-]?\d*\.?\d*)\s*,\s*([+-]?\d*\.?\d*)\s*,\s*([+-]?\d*\.?\d*)\s*,\s*([+-]?\d*\.?\d*)\)$/';
/** @var string COLOR_RGB A RegEx for rgb(255, 255, 255) etc (with percentage support) */
const COLOR_RGB = '/^rgb\(([+-]?\d*\.?\d*%?)\s*,\s*([+-]?\d*\.?\d*%?)\s*,\s*([+-]?\d*\.?\d*%?)\)$/';
/** @var string COLOR_RGBA A RegEx for rgba(255, 255, 255, 0.5) etc (with percentage support) */
const COLOR_RGBA = '/^rgba\(([+-]?\d*\.?\d*%?)\s*,\s*([+-]?\d*\.?\d*%?)\s*,\s*([+-]?\d*\.?\d*%?)\s*,\s*([+-]?\d*\.?\d*)\)$/';

/**
* Converts any valid SVG length string into an absolute pixel length,
Expand Down Expand Up @@ -82,13 +82,13 @@ public static function parseColor($color)
$g = hexdec($matches[2].$matches[2]);
$b = hexdec($matches[3].$matches[3]);
} elseif (preg_match(self::COLOR_RGB, $color, $matches)) {
$r = intval($matches[1]);
$g = intval($matches[2]);
$b = intval($matches[3]);
$r = self::parseRGBComponent($matches[1]);
$g = self::parseRGBComponent($matches[2]);
$b = self::parseRGBComponent($matches[3]);
} elseif (preg_match(self::COLOR_RGBA, $color, $matches)) {
$r = intval($matches[1]);
$g = intval($matches[2]);
$b = intval($matches[3]);
$r = self::parseRGBComponent($matches[1]);
$g = self::parseRGBComponent($matches[2]);
$b = self::parseRGBComponent($matches[3]);
$a = intval(floatval($matches[4]) * 255);
}

Expand All @@ -100,6 +100,24 @@ public static function parseColor($color)
return array($r, $g, $b, $a);
}

/**
* Converts the provided component string (either percentage or number)
* into a color component int (0 - 255).
*
* @param string $component The component string.
*
* @return int The parsed component int (0 - 255).
*/
private static function parseRGBComponent($component)
{
$matches = array();
if (preg_match('/^([+-]?\d*\.?\d*)%$/', $component, $matches)) {
return intval(floatval($matches[1]) * (255 / 100));
}

return intval($component);
}

/**
* @var array[] $namedColors A map of color names to their RGBA arrays.
* @see https://www.w3.org/TR/SVG11/types.html#ColorKeywords For the source.
Expand Down

0 comments on commit 81136fa

Please sign in to comment.