Logo

Programming-Idioms

  • D
  • Js

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.

var c = "#";
for(var i = 0; i<3; i++) {
  var sub1 = c1.substring(1+2*i, 3+2*i);
  var sub2 = c2.substring(1+2*i, 3+2*i);
  var v1 = parseInt(sub1, 16);
  var v2 = parseInt(sub2, 16);
  var v = Math.floor((v1 + v2) / 2);
  var sub = v.toString(16).toUpperCase();
  var padsub = ('0'+sub).slice(-2);
  c += padsub;
}
c = "#" + (() => {
  const [p1, p2] = [c1, c2].map((color) => parseInt(color.slice(1), 16)),
    a = [];

  for (let i = 0; i <= 2; i += 1) {
    a.push(Math.floor(((p1 >> (i * 8) & 0xff) + (p2 >> (i * 8) & 0xff)) / 2));
  }

  return a.reverse().map((num) => num.toString(16).padStart(2, "0")).join("");
})();
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))("#");
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