Logo

Programming-Idioms

  • Ruby
  • Fortran

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.

character (len=7) :: c, c1, c2
integer, dimension(3) :: v, v1, v2

read (unit=c1,fmt='(X,3Z2)') v1
read (unit=c2,fmt='(X,3Z2)') v2
v = (v1 + v2)/2
write (unit=c,fmt='("#",3Z2)') v
rgbs = c1[1..-1].scan(/../), c2[1..-1].scan(/../)
c = "#%02X%02X%02X" % rgbs.transpose.map{|h1, h2| (h1.hex + h2.hex)/2 }
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