Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #154 Halfway between two hex color codes

Find color c, the average between colors c1, c2.

c, c1, c2 are strings of hex color codes: 7 chars, beginning with a number sign # .
Assume linear computations, ignore gamma corrections.

use List::SomeUtils qw(pairwise);
my @c1 = unpack 'xA2A2A2', $c1;
my @c2 = unpack 'xA2A2A2', $c2;
my $c = sprintf '#%02X%02X%02X', pairwise { (hex($a) + hex($b)) / 2 } @c1, @c2
using System.Drawing;
Color color1 = ColorTranslator.FromHtml(c1);
Color color2 = ColorTranslator.FromHtml(c2);
c = string.Format($"#{((color1.R + color2.R) / 2):X2}{((color1.G + color2.G) / 2):X2}{((color1.B + color2.B) / 2):X2}");

New implementation...
< >
programming-idioms.org