Az Expattech az ünnepek alatt (dec.24-jan.1.) zárva tart. Nyitás: 2024.január 2

ExpatTech Techblog

Peter Todd 2010.09.28. 12:15

Flash Cookbook - Colors - Part 1. Grayscale Displayobjects

To set a displayobject grayscale we use a ColorMatrixFilter. To initialize the ColorMatrixFilter we need an array with specific elements in it:

var grayscale:Array = [
                                   0.3536, 0.3536, 0.3536, 0, 0,
                                   0.3536, 0.3536, 0.3536, 0, 0,
                                   0.3536, 0.3536, 0.3536, 0, 0,
                                   0, 0, 0, 1, 0
                                   ];

For now, it's enough if we state, that each row in this array represents the red, green, blue and alpha channels respectively.

We use an approximation for the values ([squarerootof 2] / 4 = 0.3536).

To initialize the filter do:

var grayscalefilter:ColorMatrixFilter = new ColorMatrixFilter(grayscale);

and so to apply it to a displayobject, assign it to its filters property:

object.filters = [grayscalefilter];

Furthermore here we can create a nice static function. If it gets a parameter, then it applies it to the object (given as parameter), and also it returns the filter:

static public function grayscale(object:DisplayObject = null):ColorMatrixFilter
{
    var grayscale:Array = [
                           0.3536, 0.3536, 0.3536, 0, 0,
                           0.3536, 0.3536, 0.3536, 0, 0,
                           0.3536, 0.3536, 0.3536, 0, 0,
                           0, 0, 0, 1, 0
                           ];
    
    if(object != null)
    {
        var arr:Array = object.filters;
        arr = arr.concat([new ColorMatrixFilter(grayscale)]);
        object.filters = arr;
       
        return new ColorMatrixFilter(grayscale);
    }
    
    return new ColorMatrixFilter(grayscale);
}

Note that first it buffers the filters of the objects, adds the grayscale filter to this array then puts it back to the object's filters.

Tags: