AS3 - 动态改变元件的颜色
Flex开发中,有时会需要通过代码调整设置组件的颜色,下面演示了两种做法。
方法2:不会丢失细节,更好(这种做法的话,原始元件需要用黑白灰来制作,以达到最好的效果)
方法1:将元件内所有的颜色都替换成另一种颜色(透明度会保留),效果图如下:
<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="init()" fontFamily="微软雅黑"> <fx:Script> <![CDATA[ private function init():void{ setRGB(cav2,0xff00ff); } public static function setRGB(obj:DisplayObject, color:uint):void{ var c:ColorTransform = new ColorTransform(); c.color = color; obj.transform.colorTransform = c; } ]]> </fx:Script> <s:layout> <s:HorizontalLayout paddingLeft="50" paddingTop="50"/> </s:layout> <s:Group id="cav1" width="100" height="100"> <s:Rect width="100%" height="100%"> <s:fill> <s:SolidColor color="0x00cc00" alpha="0.4"/> </s:fill> <s:stroke> <s:SolidColorStroke color="0x00cc00" weight="6"/> </s:stroke> </s:Rect> <s:Label text="正常" x="35" y="40"/> </s:Group> <s:Group id="cav2" width="100" height="100"> <s:Rect width="100%" height="100%"> <s:fill> <s:SolidColor color="0x00cc00" alpha="0.4"/> </s:fill> <s:stroke> <s:SolidColorStroke color="0x008800" weight="6"/> </s:stroke> </s:Rect> <s:Label text="变色" x="35" y="40"/> </s:Group> </s:Application>
方法2:不会丢失细节,更好(这种做法的话,原始元件需要用黑白灰来制作,以达到最好的效果)
public function transformColor(obj:Object,color:Number):void { if (obj==null) return; var c:ColorTransform=new ColorTransform(); c.color=color; var ct:ColorTransform; //ct=new ColorTransform(1,1,1,1,c.redOffset-127,c.greenOffset-127,c.blueOffset-127,0); ct=new ColorTransform(1,1,1,1,c.redOffset,c.greenOffset,c.blueOffset,0); obj.transform.colorTransform=ct; }