AS3 – Color functions

April 24th, 2009 at 12:47 pm by Rick

This class lets you manipulate color information.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package ca.revoke.utils {

    public class Tint {

        public static function lighten(color:Number, ratio:Number):Number{
            var rgb:Object = getRGB(color);
            for (var ele in rgb){
                rgb[ele] += (255 - rgb[ele]) * ratio;
            }
            return getHex(rgb.r, rgb.g, rgb.b);
        }

        public static function darken(color:Number, ratio:Number):Number{
            var rgb:Object = getRGB(color);
            for (var ele in rgb){
                rgb[ele] = rgb[ele] * (1-ratio);
            }
            return (getHex(rgb.r, rgb.g, rgb.b));
        }

        public static function getHex(r:Number, g:Number, b:Number):Number{
            var rgb:String = "0x" + (r<16?"0":"") + r.toString(16) + (g<16?"0":"") + g.toString(16) + (b<16?"0":"") + b.toString(16);
            return Number(rgb);
        }

        public static function getRGB(color:Number):Object{
            var r = color >> 16 & 0xFF;
            var g = color >> 8 & 0xFF;
            var b = color & 0xFF;
            return {r:r, g:g, b:b};
        }

        public static function blend(color1:Number, color2:Number, ratio:Number):Number{
            var rgb1:Object = getRGB(color1);
            var rgb2:Object = getRGB(color2);
            for (var ele in rgb1){
                rgb1[ele] = rgb1[ele] + (rgb2[ele] - rgb1[ele]) * ratio;
                if (rgb1[ele] > 255) rgb1[ele] = 255;
                if (rgb1[ele] < 0) rgb1[ele] = 0;
            }
            return getHex(rgb1.r, rgb1.g, rgb1.b);
        }

    }

}

3 Responses to “AS3 – Color functions”

  1. Joeri says:

    Hmm, when I pass 0xf0ff00 to the darken method, I get green instead of dark yellow….

  2. Dan says:

    There’s a problem with the getHex function whereby if either r, g or b are zero, the toString call will return just a single zero. This will mess up the hex string as it needs to be represented as two zeros. That’s why you got a mess passing 0xf0ff00. Fix the getHex function and it works just fine (so thanks!).

  3. Rick says:

    @Dan: Thanks for resolving the problem! I updated the getHex function.