
How To Calculate The Average Between 2 Colors In ActionScript 3.0
June 6, 2020In 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.
- package net.scratchbrain.color
- {
- import net.scratchbrain.color.AverageColor;
- public class AverageColor
- {
- public static function averageHex(_hex1:uint,_hex2:uint):uint
- {
- var rgb1:Object = ConvertColor.HexToRGB(_hex1);
- var rgb2:Object = ConvertColor.HexToRGB(_hex2);
- var hsb1:Object = ConvertColor.RGBToHSB(rgb1.r,rgb1.g,rgb1.b);
- var hsb2:Object = ConvertColor.RGBToHSB(rgb2.r,rgb2.g,rgb2.b);
- return averageHsb(hsb1.h,hsb1.s,hsb1.b,hsb2.h,hsb2.s,hsb2.b);
- }
- public static function averageRgb(_r1:int,_g1:int,_b1:int,_r2:int,_g2:int,_b2:int):uint
- {
- var hsb1:Object = ConvertColor.RGBToHSB(_r1,_g1,_b1);
- var hsb2:Object = ConvertColor.RGBToHSB(_r2,_g2,_b2);
- return averageHsb(hsb1.h,hsb1.s,hsb1.b,hsb2.h,hsb2.s,hsb2.b);
- }
- public static function averageHsb(_h1:int,_s1:int,_b1:int,_h2:int,_s2:int,_b2:int):uint
- {
- var _h:int;
- var _s:int;
- var _b:int;
- if(_h1 <= 18 && _s1 != 0 && _h2 >= 180){
- _h1 = 360;
- }
- if(_h2 <= 18 && _s2 != 0 && _h1 >= 180){
- _h2 = 360;
- }
- if(_s1 != 0 && _s2 != 0){
- _h = (_h1 + _h2)/2;
- _s = (_s1 + _s2)/2;
- _b = (_b1 + _b2)/2;
- }else if(_s1 == 0 && _s2 == 0 _h = 0;
- _s = 0;
- _b = (_b1 + _b2)/2;
- }else
- _h = (_h1 != 0) ? _h1 : _h2;
- _s = (_s1 + _s2)/2;
- _b = (_b1 + _b2)/2;
- }
- var rgb:Object = ConvertColor.HSBToRGB(_h,_s,_b);
- return ConvertColor.RGBToHex(rgb.r,rgb.g,rgb.b);
- }
- }
- }