Did you know…
You can dynamically change a display elements style and attributes by utilizing custom style tags in conjunction with the setStyle/GetStyle methods of the component to which the style is applied to? Let’s walk through a simple example to illustrate.
A simple gradient border skin as illustrated below.
package com.thekeunster.skins
{
import flash.display.Graphics;
import flash.geom.Matrix;
import mx.core.EdgeMetrics;
import mx.skins.halo.HaloBorder;
[Style(name="fillColors", type="Array", inherit="no")]
public class SimpleGradientSkin extends HaloBorder
{
private var fillColors:Array;
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
fillColors = getStyle("fillColors") as Array;
if (!fillColors) fillColors = [0xFFFFFF, 0xFFFFFF];
var g:Graphics = graphics;
var b:EdgeMetrics = borderMetrics;
var w:Number = unscaledWidth - b.left - b.right;
var h:Number = unscaledHeight - b.top - b.bottom;
var m:Matrix = verticalGradientMatrix(0, 0, w, h);
g.clear();
g.beginGradientFill("linear", fillColors, [1, 1], [0, 255], m);
g.drawRect(0,0,w,h);
g.endFill();
}
}
}
Then applying that border skin to a canvas, as illustrated below. W/in the “switchGradient” method, you’ll notice that we’re switching out the gradient’s fillColors dynamically via “setStyle”. In the borderSkin, we reference the fill colors via “getStyle”.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Style>
.simpleBorderSkin
{
fillColors : #ff0000, #0000ff;
borderSkin : ClassReference('com.thekeunster.skins.SimpleGradientSkin');
}
</mx:Style>
<mx:Script>
<![CDATA[
private function switchGradient( event : Event ) : void
{
// dynamically switch the border skins gradient fillColor with random color values
content.setStyle( "fillColors", [ Math.random() * 0xff0000, Math.random() * 0x00ff00 ] );
}
]]>
</mx:Script>
<mx:Button label="Switch Gradient" click="{ switchGradient( event ) }" />
<mx:Canvas styleName="simpleBorderSkin" id="content" left="30" right="30" bottom="30" top="30" />
</mx:Application>