Not yet rated

Problem

You want to dynamically add effects to or remove them from a component at runtime.

Solution

Create a new Array, copying in any filters currently applied to the component that you want to keep (and adding new ones if desired), and reset the filters property of the component to that Array.

Detailed explanation

Every UIComponent defines a filters property that contains all the filters applied to that component. To update those filters, you need to set the filters property to a new Array. To begin, you need code similar to this:

<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
         xmlns:s="library://ns.adobe.com/flex/spark"
         xmlns:mx="library://ns.adobe.com/flex/halo" width="400" height="300">
    <fx:Declarations>
        <!-- Place nonvisual elements (e.g., services, value objects) here -->
    </fx:Declarations>

    <s:layout>
        <s:HorizontalLayout/>
    </s:layout>

    <fx:Script>
        <![CDATA[

            import flash.filters.*;

            protected const BLUR:Class = flash.filters.BlurFilter;
            protected const GLOW:Class = flash.filters.GlowFilter;
            protected const SHADOW:Class = flash.filters.DropShadowFilter;

            protected function addFilter(value:Class):void {

Copy all the filters that have already been applied to the component into a new Array, and add the new one (if you didn't copy over the existing filters, only the most recently created filter would be applied to the component). Then set the filters property to the new Array:

var arr:Array = this.filters.concat();
                var fil:BitmapFilter = new value() as BitmapFilter;
                arr.push(fil);
                filters = arr;
            }

        ]]>
    </fx:Script>

    <s:Button click="addFilter(BLUR)" label="Blur"/>
    <s:Button click="addFilter(GLOW)" label="Glow"/>
    <s:Button click="addFilter(SHADOW)" label="Shadow"/>

</s: Group>

To set filters for a component in MXML, simply create BitmapFilter instances within the component's <s:filters> tag:

<s:filters>
    <s:BlurFilter/>
    <s:GlowFilter/>
</s:filters>

This recipe was originally contributed by Joshua Noble as part of O'Reilly's Flex 4 Cookbook.


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes