mike chambers | about

Using Custom Pixel Bender Filter Classes in MXML

Monday, September 8, 2008

Ok. Last post on Pixel Bender for today (I promise). This one is simple, but ties together my previous posts.

Now, that we know how to load and use Pixel Bender filters in Flex, and know how encapsulte Pixel Bender filters in an ActionScript class, lets combine the two to leverage custom Pixel Bender filters in MXML.

First, again, we need our custom Pixel Bender class:

Filter Class : TestFilter.as

package
{
    import flash.display.Shader;
    import flash.filters.ShaderFilter;
    import flash.utils.ByteArray;
        
    public class TestFilter extends ShaderFilter
    {
        //the file that contains the binary bytes of the PixelBender filter
        [Embed("testfilter.pbj", mimeType="application/octet-stream")]
        private var Filter:Class;     
        
        private var _shader:Shader;
        
        public function TestFilter(value:Number = 50)
        {
            //initialize the ShaderFilter with the PixelBender filter we
            //embedded
            _shader = new Shader(new Filter() as ByteArray);
            
            //set the default value
            this.value = value;
            super(_shader);
        }
        
        
        //This filter only has one value, named value
        public function get value():Number
        {
            return _shader.data.amount.value[];  
        }
        
        public function set value(value:Number):void
        {
            //not that pixel bender filters take an array of values, even
            //though we only have one in our example
            _shader.data.amount.value = [value];
        }       

    }
}

Once we have defined that, we can then treat the class like any other filter, and use it directly within MXML, like so:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
    xmlns:local="*"
    >
    <mx:Image left="10" top="10" width="375" height="500" source="@Embed(source='image.jpg')">
        <mx:filters>
            <local:TestFilter value="25" />
        </mx:filters>
    </mx:Image>    
</mx:Application>

Note that the local namespace maps to the package that contains our custom filter (in this case, the root package).

Compiled using the Flex 3.1.0.2710 SDK, and requires Flash Player 10. The Flex team is working on making this workflow even easier for Flex 4, so keep an eye on the Flex 4 project page.

You can see an example of the filter here.

You can find more information on Pixel Bender here.

You can download the filter from here

twitter github flickr behance