forked from ILIAS-eLearning/ILIAS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Color.php
107 lines (94 loc) · 2.28 KB
/
Color.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
declare(strict_types=1);
/* Copyright (c) 2017 Nils Haagen <[email protected]> Extended GPL, see docs/LICENSE */
namespace ILIAS\Data;
/**
* Color expresses a certain color by giving the mixing ratio
* in the RGB color space.
*
* @author Nils Haagen <[email protected]>
*/
class Color
{
protected int $r;
protected int $g;
protected int $b;
public function __construct(int $r, int $g, int $b)
{
if ($r < 0 || $r > 255) {
throw new \InvalidArgumentException("Unexpected value for \$r: '$r'");
}
if ($g < 0 || $g > 255) {
throw new \InvalidArgumentException("Unexpected value for \$g: '$g'");
}
if ($b < 0 || $b > 255) {
throw new \InvalidArgumentException("Unexpected value for \$b: '$b'");
}
$this->r = $r;
$this->g = $g;
$this->b = $b;
}
/**
* Get the valule for red.
*/
public function r(): int
{
return $this->r;
}
/**
* Get the valule for green.
*/
public function g(): int
{
return $this->g;
}
/**
* Get the valule for blue.
*/
public function b(): int
{
return $this->b;
}
/**
* Return array with RGB-values.
*
* @return int[]
*/
public function asArray(): array
{
return array(
$this->r,
$this->g,
$this->b
);
}
/**
* Return color-value in hex-format.
*/
public function asHex(): string
{
$hex = '#';
foreach ($this->asArray() as $value) {
$hex .= str_pad(dechex($value), 2, '0', STR_PAD_LEFT);
}
return $hex;
}
/**
* Return string with RGB-notation
*/
public function asRGBString(): string
{
return 'rgb(' . implode(', ', $this->asArray()) . ')';
}
/**
* Based on https://de.wikipedia.org/wiki/Luminanz
* this function decides if the color can be considered "dark".
* With a dark background, i.e., a lighter (white) color should be used
* for the foreground.
*/
public function isDark(): bool
{
$sum = 0.299 * $this->r + 0.587 * $this->g + 0.114 * $this->b;
return $sum < 128;
}
}