function ColorBackgroudFormatter::lightness
Same name in other branches
- 3.x modules/field_example/src/Plugin/Field/FieldFormatter/ColorBackgroudFormatter.php \Drupal\field_example\Plugin\Field\FieldFormatter\ColorBackgroudFormatter::lightness()
Determine lightness of a color.
This might not be the best way to determine if the contrast between the foreground and background colors is legible. But it'll work well enough for this demonstration.
Logic from https://stackoverflow.com/a/12228730/8616016.
Parameters
string $color: A color in hex format, leading '#' is optional.
Return value
float Percentage of lightness of the provided color.
1 call to ColorBackgroudFormatter::lightness()
- ColorBackgroudFormatter::viewElements in modules/
field_example/ src/ Plugin/ Field/ FieldFormatter/ ColorBackgroudFormatter.php - Builds a renderable array for a field value.
File
-
modules/
field_example/ src/ Plugin/ Field/ FieldFormatter/ ColorBackgroudFormatter.php, line 129
Class
- ColorBackgroudFormatter
- Plugin implementation of the 'field_example_color_background' formatter.
Namespace
Drupal\field_example\Plugin\Field\FieldFormatterCode
protected function lightness(string $color) {
$hex = ltrim($color, '#');
// Convert the hex string to RGB.
$r = hexdec($hex[0] . $hex[1]);
$g = hexdec($hex[2] . $hex[3]);
$b = hexdec($hex[4] . $hex[5]);
// Calculate the HSL lightness value and return that as a percent.
return (max($r, $g, $b) + min($r, $g, $b)) / 510.0 * 100;
}