Logo

Programming-Idioms

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

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.

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}");
import std.algorithm, std.range; 
import std.conv, std.array, std.format;
string c = roundRobin(c1.dropOne.chunks(2), c2.dropOne.chunks(2))
    .map!(a => a.to!int(16)).array
    .chunks(2)
    .map!(a => ((a[0] + a[1]) / 2))
    .fold!((a,b) => a ~= "%.2X".format(b))("#");

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