How To Calculate The Average Between 2 Colors In ActionScript 3.0

June 6, 2020 By Shannon Hayes Off

In some web apps or flash games, we probably need to calculate the average between 2 colors, for example. feed 0xAA0000 and 0xCC0000, and return 0xBB0000 ? Is there a simple way to calculate between two hex colors?

AverageColor is a open source(Licensed under the MIT License) util-class to calculate the average between 2 colors (Hex, RGB or HSB format).

 

 

There are only 2 classes in AverageColor library. Calculate the average color with AverageColor.as, and convert RGB/HSB/16 color with ConvertColor.as class. They were released by scratchbrain(Japanese).You can download AverageColor library here.

AverageColor.as

Function averageHex: average 2 hex colors.Function averageRgb: average 2 RGB colors.Function averageHsb: average 2 HSBcolors.

  1. package net.scratchbrain.color
  2. {
  3.     import net.scratchbrain.color.AverageColor;
  4.     public class AverageColor
  5.     {
  6.         public static function averageHex(_hex1:uint,_hex2:uint):uint
  7.         {
  8.             var rgb1:Object = ConvertColor.HexToRGB(_hex1);
  9.             var rgb2:Object = ConvertColor.HexToRGB(_hex2);
  10.             var hsb1:Object = ConvertColor.RGBToHSB(rgb1.r,rgb1.g,rgb1.b);
  11.             var hsb2:Object = ConvertColor.RGBToHSB(rgb2.r,rgb2.g,rgb2.b);
  12.             return averageHsb(hsb1.h,hsb1.s,hsb1.b,hsb2.h,hsb2.s,hsb2.b);
  13.         }
  14.         public static function averageRgb(_r1:int,_g1:int,_b1:int,_r2:int,_g2:int,_b2:int):uint
  15.         {
  16.             var hsb1:Object = ConvertColor.RGBToHSB(_r1,_g1,_b1);
  17.             var hsb2:Object = ConvertColor.RGBToHSB(_r2,_g2,_b2);
  18.             return averageHsb(hsb1.h,hsb1.s,hsb1.b,hsb2.h,hsb2.s,hsb2.b);
  19.         }
  20.         public static function averageHsb(_h1:int,_s1:int,_b1:int,_h2:int,_s2:int,_b2:int):uint
  21.         {
  22.             var _h:int;
  23.             var _s:int;
  24.             var _b:int;
  25.             if(_h1 <= 18 && _s1 != 0 && _h2 >= 180){
  26.                 _h1 = 360;
  27.             }
  28.             if(_h2 <= 18 && _s2 != 0 && _h1 >= 180){
  29.                 _h2 = 360;
  30.             }
  31.             if(_s1 != 0 && _s2 != 0){
  32.                 _h = (_h1 + _h2)/2;
  33.                 _s = (_s1 + _s2)/2;
  34.                 _b = (_b1 + _b2)/2;
  35.             }else if(_s1 == 0 && _s2 == 0                _h = 0;
  36.                 _s = 0;
  37.                 _b = (_b1 + _b2)/2;
  38.             }else
  39.                 _h = (_h1 != 0) ? _h1 : _h2;
  40.                 _s = (_s1 + _s2)/2;
  41.                 _b = (_b1 + _b2)/2;
  42.             }
  43.             var rgb:Object = ConvertColor.HSBToRGB(_h,_s,_b);
  44.             return ConvertColor.RGBToHex(rgb.r,rgb.g,rgb.b);
  45.         }
  46.     }
  47. }