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 */ 17 18declare(strict_types=1); 19 20namespace Fisharebest\Webtrees\Statistics\Service; 21 22/** 23 * Functions for managing and manipulating colors. 24 */ 25class ColorService 26{ 27 /** 28 * Interpolates the number of color steps between a given start and end color. 29 * 30 * @param string $startColor The start color 31 * @param string $endColor The end color 32 * @param int $steps The number of steps to interpolate 33 * 34 * @return array 35 */ 36 public function interpolateRgb(string $startColor, string $endColor, int $steps): array 37 { 38 if (!$steps) { 39 return []; 40 } 41 42 $s = $this->hexToRgb($startColor); 43 $e = $this->hexToRgb($endColor); 44 $colors = []; 45 $factorR = ($e[0] - $s[0]) / $steps; 46 $factorG = ($e[1] - $s[1]) / $steps; 47 $factorB = ($e[2] - $s[2]) / $steps; 48 49 for ($x = 1; $x < $steps; ++$x) { 50 $colors[] = $this->rgbToHex( 51 (int) round($s[0] + ($factorR * $x)), 52 (int) round($s[1] + ($factorG * $x)), 53 (int) round($s[2] + ($factorB * $x)) 54 ); 55 } 56 57 $colors[] = $this->rgbToHex($e[0], $e[1], $e[2]); 58 59 return $colors; 60 } 61 62 /** 63 * Converts the color values to the HTML hex representation. 64 * 65 * @param int $r The red color value 66 * @param int $g The green color value 67 * @param int $b The blue color value 68 * 69 * @return string 70 */ 71 private function rgbToHex(int $r, int $g, int $b): string 72 { 73 return sprintf('#%02x%02x%02x', $r, $g, $b); 74 } 75 76 /** 77 * Converts the HTML color hex representation to an array of color values. 78 * 79 * @param string $hex The HTML hex color code 80 * 81 * @return array 82 */ 83 private function hexToRgb(string $hex): array 84 { 85 return array_map('hexdec', str_split(ltrim($hex, '#'), 2)); 86 } 87} 88