1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2019 webtrees development team 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License as published by 8 * the Free Software Foundation, either version 3 of the License, or 9 * (at your option) any later version. 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17declare(strict_types=1); 18 19namespace Fisharebest\Webtrees\Statistics\Service; 20 21/** 22 * Functions for managing and manipulating colors. 23 */ 24class ColorService 25{ 26 /** 27 * Interpolates the number of color steps between a given start and end color. 28 * 29 * @param string $startColor The start color 30 * @param string $endColor The end color 31 * @param int $steps The number of steps to interpolate 32 * 33 * @return array 34 */ 35 public function interpolateRgb(string $startColor, string $endColor, int $steps): array 36 { 37 if (!$steps) { 38 return []; 39 } 40 41 $s = $this->hexToRgb($startColor); 42 $e = $this->hexToRgb($endColor); 43 $colors = []; 44 $factorR = ($e[0] - $s[0]) / $steps; 45 $factorG = ($e[1] - $s[1]) / $steps; 46 $factorB = ($e[2] - $s[2]) / $steps; 47 48 for ($x = 1; $x < $steps; ++$x) { 49 $colors[] = $this->rgbToHex( 50 (int) round($s[0] + ($factorR * $x)), 51 (int) round($s[1] + ($factorG * $x)), 52 (int) round($s[2] + ($factorB * $x)) 53 ); 54 } 55 56 $colors[] = $this->rgbToHex($e[0], $e[1], $e[2]); 57 58 return $colors; 59 } 60 61 /** 62 * Converts the color values to the HTML hex representation. 63 * 64 * @param int $r The red color value 65 * @param int $g The green color value 66 * @param int $b The blue color value 67 * 68 * @return string 69 */ 70 private function rgbToHex(int $r, int $g, int $b): string 71 { 72 return sprintf('#%02x%02x%02x', $r, $g, $b); 73 } 74 75 /** 76 * Converts the HTML color hex representation to an array of color values. 77 * 78 * @param string $hex The HTML hex color code 79 * 80 * @return array 81 */ 82 private function hexToRgb(string $hex): array 83 { 84 return array_map('hexdec', str_split(ltrim($hex, '#'), 2)); 85 } 86} 87