Archive for the 'Flex/Flash' Category

export to excel from flex

Flex/Flash 无评论 »

// ACTION SCRIPT FOR YOUR FLEX APP
function doCopy(dg)
{
    var font = dg.getStyle('fontFamily');
    var size = dg.getStyle('fontSize');
    var hcolor ;
    if (dg.getStyle("headerColor") != undefined)
        hcolor = [dg.getStyle("headerColor")];
    else
        hcolor = dg.getStyle("headerColors");
    var str:String = '<html><body><table width="'+dg.width+'"><thead><tr width="'+dg.width+'" style="background-color:#' +Number((hcolor[0])).toString(16)+'">';
    for (var i=0;i<dg.__columns.length;i++) {
        var colors = dg.getStyle("themeColor");
        var style = 'style="font-family:'+font+';font-size:'+size+'pt;"';
        if (dg.__columns[i].headerText != undefined) {
            str+="<th "+style+">"+dg.__columns[i].headerText+"</th>";
        }
       else {
            str+= "<th "+style+">"+dg.__columns[i].columnName+"</th>";
       }
    }
    str += "</tr></thead><tbody>";
    var colors = dg.getStyle("alternatingRowColors");
    for (var j=0;j<dg.length;j++) {
         str+="<tr width=\""+Math.ceil(dg.width)+"\" style='background-color:#" +Number((colors[j%colors.length])).toString(16)+"'>";
         var style = 'style="font-family:'+font+';font-size:'+size+'pt;"';
         for (var i=0;i<dg.__columns.length;i++) {
              if (dg.getItemAt(j) != undefined && dg.getItemAt(j) != null)
                  if (dg.__columns[i].labelFunction != undefined)
                     str += "<td width=\""+Math.ceil(dg.__columns[i].width)+"\" "+style+">"+ dg.__columns[i].labelFunction(dg.getItemAt(j),dg.__columns[i].columnName)+"</td>";
                  else
                     str += "<td width=\""+Math.ceil(dg.__columns[i].width)+"\" "+style+">"+ dg.getItemAt(j)[dg.__columns[i].columnName]+"</td>";
         }
         str += "</tr>";
    }
    str+="</tbody></table></body></html>";
    System.setClipboard(str);
}

function handleOnKeyUp()
{
    if (Key.isDown(Key.CONTROL) &&Key.getCode() ==67) {
       mx.managers.CursorManager.setBusyCursor();
       doCopy(grid);  // exchange 'grid' with the id of your datagrid you want copied
       mx.managers.CursorManager.removeBusyCursor();
    }
}

// only register interest if you want ctrl-c to process a copy of a datagrid.
// it's also ctrl + c (on key up, not down)
var obj:Object;
function registerKeyInterest()
{
    if (obj == undefined) {
        obj = new Object();
        obj.onKeyUp = mx.utils.Delegate.create(this,handleOnKeyUp);
    }
    Key.addListener(obj);
}
function removeKeyInterest()
{
    Key.removeListener(obj);
}
function copyAndOpen(grid)
{
    doCopy(grid);
    getUrl("javascript:openExcel();");
}

// JAVASCRIPT for your HTML PAGE
<SCRIPT Language="JavaScript1.2">
     var excel = null;
     function openExcel()
     {
         try {
              if (excel == null) {
                   excel = new ActiveXObject("Excel.Application");
              }
              var workbook = excel.Workbooks.Add();
              workbook.Activate();
              var worksheet = workbook.Worksheets("Sheet1");
              worksheet.Activate();
              worksheet.Paste();
              excel.visible=true;
         }
        catch(exception) {
              window.alert("Now you may Paste into an Excel SpreadSheet");
        }
    }
</SCRIPT>

Tags »||

将flex页面数据导出到excel

Flex/Flash 无评论 »

本例实现将flex中的数据利用as3xls-1[1].0.swc导出到excel文件中

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
                import mx.controls.CheckBox;
                import mx.controls.Alert;
                import com.as3xls.xls.ExcelFile;
                import com.as3xls.xls.Sheet;
                import flash.filesystem.*;

               [Bindable]
               private var dp:Array = [
                                                        {idx:1, names: "test1", sex: "b" },
                                                        {idx:2, names: "test2", sex: "g" }
                                                      ];
               public function doSelect(o:Object):void
               {
                       Alert.show("行的数据分别是:"+o.idx+"/"+o.names+"/"+o.sex);
               }

               private var sheet:Sheet;
               private function onCreate():void
               {
                        var excelFile:ExcelFile = new ExcelFile();
                        sheet = new Sheet();
                        sheet.resize(10, 10);
                        sheet.setCell(0, 0, "Today's date:");
                        sheet.setCell(0, 1, new Date());
                        excelFile.sheets.addItem(sheet);
                        var mbytes:ByteArray = excelFile.saveToByteArray();

                        var stream:FileStream = new FileStream();
                        var docsDir:File = File.documentsDirectory.resolvePath("abc.xls");  // 定死文件名

                        try {
                                 docsDir.browseForSave("Save As");
                                 docsDir.addEventListener(Event.SELECT, saveData);
                        }
                       catch (error:Error) {
                                 trace("Failed:", error.message)
                        }

                       function saveData(event:Event):void
                       {
                                 var newFile:File = event.target as File; 

                                 if (!newFile.exists) {
                                         var stream:FileStream = new FileStream();
                                         stream.open(newFile, FileMode.WRITE);
                                         stream.writeBytes(mbytes);
                                         // 写文件流
                                         stream.close();
                                 }
                       }
             }
         ]]>
       </mx:Script>

<mx:Panel>

     <mx:Button   label="导出" click="onCreate()"/>
     <mx:DataGrid id="dg1"  dataProvider ="{dp}">
         <mx:columns>
                 <mx:DataGridColumn  width="20" headerText="" >
                       <mx:itemRenderer>
                               <mx:Component>
                                     <mx:CheckBox  change=" {outerDocument.doSelect(data as Object)} "    />
                              </mx:Component>
                       </mx:itemRenderer>
                 </mx:DataGridColumn>
                 <mx:DataGridColumn headerText="names" dataField="names" width="200" />
                 <mx:DataGridColumn headerText="sex" dataField="sex" width="300" />
          </mx:columns>
      </mx:DataGrid>
</mx:Panel>

</mx:WindowedApplication>

flash.filesystem.*
需要flex AIR工程环境
在flex web application 工程环境下,没有flash.filesystem.*

Tags »|

Flex 3 Module的一个诡异bug

Flex3 无评论 »

表现:
使用ModuleManager去加载一个Module的时候, 所有的事件都激发不了.

代码:

var testModule:IModuleInfo = ModuleManager.getModule('modules/pub/User.swf');
testModule.addEventListener(ModuleEvent.READY,onModuleReady);
testModule.addEventListener(ModuleEvent.SETUP, onModuleSetup);
testModule.addEventListener(ModuleEvent.PROGRESS,onModuleLoading);
testModule.load();

打个赌, ModuleEvent里所有的事件都不会被激发.

原因:在addEventListener之后, testModule的Event Listeners就可能被GC了.
解决:不要声明局部IModuleInfo对象.

相关链接:
http://bugs.adobe.com/jira/browse/SDK-14021
https://bugs.adobe.com/jira/browse/SDK-11389

Gaurav Jain 同学说:
“References to IModuleInfo must be maintained to keep the event listeneres alive. If the IModuleInfo is defined in function local scope the event listeners may get garbage collected. ”
他表示:
“This is NAB. The weak reference was a change to fix a memory leak bug (https://bugs.adobe.com/jira/browse/SDK-9467) ”

Not a bug~ 为了修复另一个bug, 牺牲这个….

Tags »

Flex 3 ModuleEvent 事件种类

Flex3 无评论 »
Constant Defined By
ERRORString = “error”

[static] 在下载模块的时候发生错误.
ModuleEvent
PROGRESSString = “progress”

[static] 正在下载过程中.
ModuleEvent
READYString = “ready”

[static] 模块下载完毕.
ModuleEvent
SETUPString = “setup”

[static] 下载完成, 并且可以得到IFlexModuleFactory对象
ModuleEvent
UNLOADString = “unload”

[static] 模块被卸载.
ModuleEvent

官方的文档里一般都使用READY事件.
我们来确定一下, 各个事件的顺序:
设定每个事件的输出, 会得到:
0
65536
65536
254259
[SWF] modules:pub:User.swf - 572,308 bytes after decompression
Event Setup
254259
Event Ready
Setup时间早于Ready.

Tags »

使用DateField中的静态函数在字符串和日期之间互转

Flex/Flash, Flex3 无评论 »

使用DateField中的静态函数在字符串和日期之间互转

var da:Date=new Date()
trace(DateField.dateToString(da,”YYYY-MM-DD”));
var s=”01-2009-04″
var daa:Date=DateField.stringToDate(s,”MM-YYYY-DD”)
trace(daa.toDateString())

Tags »|

Loading Flex Skins at Runtime

Flex/Flash, Flex2 无评论 »

There are lots of great resources out there on how to skin your Flex applications.  Quick recap: Flex supports two approaches to skinning:  graphical and programmatic.  Graphical skinning involves creating graphical assets in Flash, Photoshop, Fireworks, etc. and embedding them in your Flex application.  Programmatic skinning involves creating an ActionScript class which defines the skin for a control.  As you might guess, graphical skinning is easier, programmatic skinning more powerful.

One drawback to both approaches is that the skinned resources (SWF/PNG/GIF/etc. for graphical skins, the AS class file for programmatic skins) must be available at compile-time for the skins to be applied.  Or do they?  In this post I’ll describe a neat trick for pulling in graphical skins at run-time (using a live demo with source code).

To make this example as simple as possible, I’m going to create a Flex app that allows the Button control to be dynamically skinned.  This app will pull down a skinning SWF at runtime, load the skins, and apply them to the Button control.  Again, to keep it simple I’m going to use the skin template file provided in NJ’s skinning article, and apply the RadioButton skins to the Button control.  (A tip of the cap to Roger Gonzalez and NJ for basically coming up with this solution.)

Step #1: Create a wrapper SWF for the skin assets

The skin assets are in the aforementioned skin template file.  I want to create a wrapper SWF that my Flex app can load at runtime and from which it can extract the appropriate assets, in this case the four symbols for the RadioButton control.  Here’s the source for wrapper SWF:

package
{
import flash.display.Sprite;

public class Wrapper extends Sprite
{
[Embed(source="flex_skins.swf",symbol="RadioButton_upIcon")]
public var rbUpSkin: Class;
[Embed(source="flex_skins.swf",symbol="RadioButton_downIcon")]
public var rbDownSkin: Class;
[Embed(source="flex_skins.swf",symbol="RadioButton_disabledIcon")]
public var rbDisabledSkin: Class;
[Embed(source="flex_skins.swf",symbol="RadioButton_overIcon")]
public var rbOverSkin: Class;
}
}

Step #2: Put the wrapper SWF on your web server

The Flex app needs to load the wrapper SWF from somewhere!

Step #3: In your Flex app, use a Loader to load the wrapper SWF

I created a utility class called ClassLoader to wrap up functionality related to loading the SWF and extracting the class.  Here are the key lines:

loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);

request = new URLRequest(swfLib);
var context:LoaderContext = new LoaderContext();
context.applicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
loader.load(request, context);

Notice that the Loader loads the SWF into an ApplicationDomain that has the current domain as its parent.  This is the key to ensuring that the app can access the loaded class and its assets.

Step #4: Get the class from the loaded SWF and instantiate it

Here we load the Class using an agreed-upon className (in this case, “Wrapper”):
阅读全文 »

Tags »|||

FLEX RSL 应用注意事项

Flex/Flash, Flex2, Flex3 无评论 »

FLEX发布体积过大是每个使用FLEX开发的朋友都知道的

那是因为FLEX在发布的时候会带一个框架文件,框架文件包含了所有的Flex内置类…
该文件大小大概是500多K,以致一个空的FLEX项目.发布后就有500多K

所以FLEX提供了RSL(runtime shared library)(运行共享库??),
让用户只需要下载相同版本的框架文件一次,然后存在FlashPlayer指定的cache目录中..
当下次再浏览应用了RSL的FLEX项目时,就不需要重新下载..从而加快加载速度.

….理论的东东不大会表达..差不多是这样吧…下面实际操作一下..

要应用RSL.我们执行下面的步骤:
1.在项目文件夹中点右建,选择”properties”-”Flex BuildPath”-”Library Path”
2.该选项卡上我们看到”FrameWork linkage”,默认是选中”Merged into cdoe”(打包在里边..大概这意思)
3.点开下拉,选择”runtime shared library(RSL)”,点”OK”

这样~我们的项目就已经使用RSL~把框架文件分离出来..
我们点开项目的bin(bin-debug)文件夹.
会看到已经生成了framework_3.0.0.477.swf和framework_3.0.0.477.swz两个文件(0,0,447是版本号).

再看看项目的swf..已经变成了50k左右(只有两三个组件)

当我们发布项目时..
只需要把framework_3.0.0.477.swf和framework_3.0.0.477.swz两个文件
跟项目swf放在一目录下传到服务器上即可…

ps:在这里说说两个值得注意的问题..

第一个是发布项目后出现RSL error..主要有两个原因:
1.使用低于9.0.115版本的FLASH PLAYER,,
2.没有把framework_3.0.0.477.swf和framework_3.0.0.477.swz传到服务器上..以至类库无法下载….

说第二个问题前..先介绍一下framework_3.0.0.477.swf和framework_3.0.0.477.swz,
其中framework_3.0.0.477.swz加载时会优先加载的..当加载成功后..会放到flash player的cache目录下.(完成RSL…).
当framework_3.0.0.477.swz下载失败的话..flashplayer会自动下载framework_3.0.0.477.swf,该文件只能下载到ie缓存..并不能达到RSL功能.,只保证项目可正常运行.

很从朋友反映..在本地浏览的时候..framework_3.0.0.477.swz可以正常加载到player的cache目录..
可是当放到服务器后..即会加载不成功..只能靠加载swf来运行..

查看对方系统路径
Documents and Settings\{username}\Application Data\Adobe\Flash Player\AssetCache\
并未发现那个526KB的SWZ文件

出现这个情况..是因为服务器的IIS不支持swz后缀的文件的下载..
(以前flv没盛行之前也出现过这类情况),
如果是自己的服务器.我们只需要配置一下iis.添加一MIME类型即可..

详细操作就不说了..MIME类型如下..
swz_mime

Tags »||

Compile multi-flex applications contained in one project with Flex Builder

Flex/Flash, Flex2, Flex3, FlexBuilder 无评论 »

One day, i want to compile my business app with TestSuiteRunner (from FlexUnit) app at one time using Flex Builder, but i never do this before. Flex Builder can not set two application once. But, it can set modules to be compiled.

1. Add a new mxml application into one existed app and named it as what you want. Mine is TestApp.mxml.

compile-multi-flex-applications-contained-in-one-project-with-flex-builder-img-11

2. Use the right key of your mouse to click your application listed in Flex Navigator, then open the Properties for yourappname dialog.

compile-multi-flex-applications-contained-in-one-project-with-flex-builder-img-21

compile-multi-flex-applications-contained-in-one-project-with-flex-builder-img-31

3. Select Flex Modules panel, “add” TestApp.mxml as a module. Do not “browse” to add TestApp.xml, you can not find it in the Select Module dialog, just edit the Source path like this “src/TestApp.mxml”. Pay attention here : you should select “Do not optimize (module can be loaded by multiple applications)” instead of the default option in order to generate a standalone SWF file.

compile-multi-flex-applications-contained-in-one-project-with-flex-builder-img-4-thumb

4.Compile your application using Build Project or Builder All as you wish. Then you can find two, or more if any, SWF files displayed in bin-debug directory.

compile-multi-flex-applications-contained-in-one-project-with-flex-builder-img-51

compile-multi-flex-applications-contained-in-one-project-with-flex-builder-img-61

Tags »

How to use FlexUnit in Flex

AS2, AS3, Flex/Flash, Flex2, Flex3 无评论 »

If you’re a java programmer, you may familiar with JUnit. Today, software testing is becoming more and more important. A good platform needs good testing tools. Now, Adobe release the unit test tool on flex named FlexUnit. So, let’s try it, and gives you a direct-viewing understand.

I’ll suppose the reader, you familiar with Flex and AS 3.0(or AS 2.0), and any knowledge about software testing is unnecessary. This demo can be ran in Flex Builder 3.0.

First thing first, we must download this tool from the official website. Open this page http://code.google.com/p/as3flexunitlib/,and you’ll see the Featured Downloads on your right hand side. Download the file named flexunit-.85.zip, and extract it.

There’ll be three directories including bin, doc and src after you extracted it. As usual, the bin directory is keeping the SWC library of FlexUnit, and the doc directory is about API documents, the last directory src is about the source code of this project.

Now, let’s build a test project to see how to use it.

clip-image004-thumb

Open your Flex Builder, create a new project called TestRunner, choose the project location, set the Application type as Web application and no server is needed.

Click Next, and you can choose the output folder, here we use the default path.

Next again, here comes the setting. Switch to the Library Path, click Add SWC, showing below.

clip-image005-thumb

clip-image007

Find the flexunit.swc, and the flexunit will added into the build path libraries. Such as the right hand side graph shows.

If you don’t want to setting it now, you can set it when you want to. You just need to right click the project, choose properties, then click the Flex Builder Path, you can see the same user interface. If you have some experience on Eclipse, you will familiar with it.
阅读全文 »

Tags »

How to Use the ASUnit Framework to Write Unit Tests for ActionScript

AS3, Flex/Flash 无评论 »

AsUnit is the first choice for Test-Driven Development using pure Flash applications.It is an Open-Source, Unit Test Framework for Macromedia Flash ActionScript 2.0 and 3.0. AsUnit 2.x is fully integrated with the Flash IDE, and there is a Mozilla XUL UI that works alongside any other ActionScript authoring tools.  This framework allows developers to easily create and manage Classes, Test Cases, Test Suites and view the results of extensive test fixtures. This article will explain in detail how to use the ASUnit framework to write unit tests for ActionScript. It is aimed at an experienced AS developer who is curious about unit testing but has been frustrated by the lack of documentation for ASUnit.

1) Create a directory called AsUnitExample
Download the asunit framework zip file from here and copy the contents of the as3 directory into your AsUnitExample directory. All of the files we create in the following example will be in the root directory AsUnitExample. At this point the AsUnitExample directory should contain the file AsUnitTestRunner.as and the directories asunit and mx.
阅读全文 »

Tags »

【转自TICORE】【HOW TO 系列】讓 Flex 內不可選擇的文字超連結生效

Flex/Flash, Flex3 无评论 »

在 Flash 內,不可選擇的 (unselectable) TextField 仍可保留 HTML 超連結功能但是 Flex 卻不行查文件上也有寫到 Label.selectable其實不光是 Label, Text 組件不行任何一個在 Flex App 下的 unselectable TextField 超連結都會失效這樣需要用到不可選擇的超連結文字時就很不方便

Flex 超連結失效測試程式:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
   fontSize="12" backgroundColor="#F0F0F0">
 <mx:Script>
  <![CDATA[
   import flash.events.*;
   import mx.managers.FocusManager;

  public function onTxtLink(evtObj:Event):void...{
    textArea.text += evtObj + " ";
   }
  ]]>
 </mx:Script>
 <mx:Label selectable="false" link="onTxtLink(event)">
  <mx:htmlText>
   <![CDATA[Flex Label : <a href='event:linkEvent'>Link Event Text</a> | ]]>
   <![CDATA[<a href='http://ticore.blogspot.com' target='_blank'>Ticore's Blog</a>]]>
  </mx:htmlText>
 </mx:Label>

 <mx:Text selectable="false" link="onTxtLink(event)">
  <mx:htmlText>
   <![CDATA[Flex Text : <a href='event:linkEvent'>Link Event Text</a> | ]]>
   <![CDATA[<a href='http://ticore.blogspot.com' target='_blank'>Ticore's Blog</a>]]>
  </mx:htmlText>
 </mx:Text>

 <mx:Button label="Clear Log" click="textArea.text = '';" />
 <mx:TextArea id="textArea" width="100%" height="100%" />
</mx:Application>

於是花了不少力氣去追蹤原因
終於發現是 Flex 內的 FocusManager 刻意攔截下 unselectable TextField Focus 事件
這也間接造成超連結失效

既然知道問題是出在 FocusManager 上
問題就比較好處理了
以下是變通方式,讓 FocusManager 短暫失效一下~

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
fontSize="12" backgroundColor="#F0F0F0">
<mx:Script>
<![CDATA[
import flash.events.*;
import mx.managers.FocusManager;

public function onTxtLink(evtObj:Event):void...{
textArea.text += evtObj + " ";
}
]]>
</mx:Script>
<mx:Label selectable="false" link="onTxtLink(event)"
rollOver="focusManager.deactivate()" rollOut="focusManager.activate()">
<mx:htmlText>
<![CDATA[Flex Label : <a href='event:linkEvent'>Link Event Text</a> | ]]>
<![CDATA[<a href='http://ticore.blogspot.com' target='_blank'>Ticore's Blog</a>]]>
</mx:htmlText>
</mx:Label>

<mx:Text selectable="false" link="onTxtLink(event)"
rollOver="focusManager.deactivate()" rollOut="focusManager.activate()">
<mx:htmlText>
<![CDATA[Flex Text : <a href='event:linkEvent'>Link Event Text</a> | ]]>
<![CDATA[<a href='http://ticore.blogspot.com' target='_blank'>Ticore's Blog</a>]]>
</mx:htmlText>
</mx:Text>

<mx:Button label="Clear Log" click="textArea.text = '';" />
<mx:TextArea id="textArea" width="100%" height="100%" />
</mx:Application>

Online Demo:

Tags »

使用图形滤镜来扩展基本的组件

Flex/Flash, Flex3 无评论 »
folders.jpg

在前面的帖子中我曾经讲到过如何使用图形滤镜,这篇博文中我将介绍如何使用这些滤镜来增强基本组件的能力,在本示例中我将展示如何使用滤镜来改变基本的TREE组件的外观
我曾经无数次的碰到过这个问题,那就是如何通过TREE图标来表示其当前的TREE展开状态

我总是在寻找将数据可视化的方法,这里有一个非常简单的方来来扩展一个基本的TREE组件的图标所蕴含的意味,我见过无数种的实现方式,但是我认为下面的是其中最简单的一种方法,它使用了ColorMatrixFilter 来改变TREE文件夹的颜色,你可以使用这项技巧将一些文件夹分组到一起,采用特定的颜色来表示树的不同层次,根据文件夹或者是数据来改变树图标的现实状态,当然还有更多

下面就是:


下面我就展示它是如何实现的,它使用了一个定制的ITEM RENDER,该render扩展了TREEITEMRENDER类,在commitProperties 方法中,应用了ColorMatrixFilter 过滤当前文件夹的图标,就是这么简单,而没有什么更换图标或者是替代之类的。

override protected function commitProperties():void
{
 	super.commitProperties();

 	if ( icon )
 	{
  		var matrix:Array = new Array();

  		switch (TreeListData( listData ).depth )
  		{
   			case 1:
   				matrix = matrix.concat([1, 0, 0, 0, 0]); // red
   				matrix = matrix.concat([0, .25, 0, 0, 0]); // green
   				matrix = matrix.concat([0, 0, .25, 0, 0]); // blue
   				matrix = matrix.concat([0, 0, 0, 1, 0]); 	// alpha
   				icon.filters = [ new ColorMatrixFilter( matrix) ]
   				break;
   			case 2:
   				matrix = matrix.concat([.25, 0, 0, 0, 0]); // red
   				matrix = matrix.concat([0, 1, 0, 0, 0]); // green
   				matrix = matrix.concat([0, 0, .25, 0, 0]); // blue
   				matrix = matrix.concat([0, 0, 0, 1, 0]); 	// alpha
   				icon.filters = [ new ColorMatrixFilter( matrix) ]
   				break;
   			case 3:
   				matrix = matrix.concat([.25, 0, 0, 0, 0]); // red
   				matrix = matrix.concat([0, .25, 0, 0, 0]); // green
   				matrix = matrix.concat([0, 0, 1, 0, 0]); // blue
   				matrix = matrix.concat([0, 0, 0, 1, 0]); 	// alpha
   				icon.filters = [ new ColorMatrixFilter( matrix) ]
   				break;
   			default:
   				icon.filters = [];
   				break;
   		}
  	}
}

当然这些代码在定制的TREE图标上也可以工作

源代码链接:
http://www.tricedesigns.com/portfolio/colorfolders/srcview/index.html

http://www.tricedesigns.com/portfolio/colorfolders/srcview/TreeColors.zip.html

Note: There are 2 separate files in there “TreeColors.mxml” and “CustomFolderTreeColors”. The only difference between these two are the specification of custom folder icons.

Tags »|

如何向事件监听器传送额外的参数

AS3, Flex/Flash, Flex2, Flex3 无评论 »

在FLEX文档中所述的是,如果你要向监听器传送参数,那么你最好使用MXML标签,但是在这里要展示给你的是如何使用AS脚本完成。

使用内联函数

solution is very simple, basically for following scenario :
arbitrary button called ABCButton,function ABCButtonListener needs to listen to click event and also receive extra parameter

“myPrivateSpecialObject”

object.

you do following :

private function ABCButtonListener(e:MouseEvent,specialObj:Object): void {
Alert.show(specialObj.name);
}

private function methodWhereyouDostuffAndRegisterListener(): void {
var myPrivateSpecialObject:Object = {name:”Special String Ingredients for Orange”};

ABCButton.addEventListener(MouseEvent.CLICK,function (e:MouseEvent) : void {
ABCButtonListener(e,myPrivateSpecialObject);
});
}

P.S —————–

you can use same structure to register listener for more than one button,for example :

private function methodWhereyouDostuffAndRegisterListener(): void {
var myPrivateSpecialObject:Object = {name:”Special String Ingredients for Orange”};

ABCButton.addEventListener(MouseEvent.CLICK,function (e:MouseEvent) : void {
ABCButtonListener(e,myPrivateSpecialObject);
});

myPrivateSpecialObject = {name:”Special Ingredients for Apple”};

OtherButtonButton.addEventListener(MouseEvent.CLICK,function (e:MouseEvent) : void {
ABCButtonListener(e,myPrivateSpecialObject);
});

}

above code registers same listener for two buttons but before registering second listener , we try to modify

myPrivateSpecialObject

so, reference is changed to have different value, but if you assume now each listener received different value , its not correct, they will both received latest assigned value . overall inline function is good technique to pass any number of parameters to a listener as long as listener is ready for those parameters.

Tags »||

使用 Flex Builder 3.x 分析工具 Profile

FlexBuilder 无评论 »

前言

关于分析工具

(原文见Flex Builder 3.x 帮助文档 About Profiling

Adobe Flex 分析工具(Profiler)能够帮助我们诊断应用程序中的性能瓶颈和内存泄漏。我们从Flex Builder中启动分析工具之后,在我们同应用程序的交互过程中,分析工具将记录应用程序的各种状态。例如,对象的数量及这些对象的大小,被调用的方法 的数量以及调用这些方法所消耗的时间。

分析应用程序能够帮助我们确定以下问题:

  • 调用频率 有时,我们会多次调用一些计算代价昂贵(耗时)的方法,而这些调用是不必要的。通过识别那些经常被调用的方法,我们能够在调节性能的过程中,专注于应用程序中对性能影响最大的地方。
  • 方法耗时 分析工具能够告诉我们一个调用特定方法所消耗的时间。如果这个方法被调用了多次,分析工具将告诉我们,在与应用程序交互的这段时间里,调用这个方法所消耗的平均时间。如果其中的一些方法造成了性能瓶颈,我们可以想办法优化一下它们。
  • 调用堆栈 通过追踪某一方法的调用堆栈,我们可以看到应用程序调用该方法的完整路径。
  • 实例数量(对象分配) 有时,我们会发现同一对象被创建了太多次,而我们只需要这一对象的几个实例。在这些情况下,如果只需要一个实例,我们可能考虑使用单件模式;如果需要多 个,则应用其他技术来减少对象分配。如果确实需要很多该对象的实例,我们得考虑优化对象本身来降低资源总数以及内存占用量。
  • 对象大小 如果观察到某些对象大小异常,我们可以尝试优化它们以减少其内存占用量。程序中某些对象被多次创建时尤为有效。
  • 垃圾回收 比较性能快照时,我们可能发现一些不再被程序使用的对象仍然在“loitering”,或者存储在内存中。为了避免内存泄漏,我们可以添加一些逻辑,来移除这些对象身上的“残余”引用。

我们不应当把性能分析看成一个与应用程序开发毫无关联,相对独立的阶段。相反,性能分析应当或多或少的集成到整个开发过程的每一阶段。我们在开发过 程中应尽可能的早进行性能分析,多进行性能分析。这样,我们才能更快的找出有问题的地方。性能分析是一个反复进行的过程,尽可能频繁的进行性能分析将使我 们受益无穷。

使用Flex Builder 3.x 分析工具

(原文见Using the Flex Builder 3.x Profiler)

最近接触了许多内存泄漏方面的问题。 现在我终于有时间将我在分析内存泄漏中用到的技术写下来了。

我创建了一个SWF文件来代替 PowerPoint。这样,在看报告的同时,大家也可以学习如何使用Profiler。在文章中,我说明了分析工具中显示的内存与通过 System.totalMemory获取的内存及进程(Flash Player, IE, Firefox)所占用内存的不同,并演示了针对内存泄漏问题中常见的两个情景,该如何分析。

查看报告(英文)

和往常一样,以下是附加的说明。

经常听到的一个话题是如何实现XML驱动或数据驱动的用户界面。在这个SWF文件中,我演示了一种实现方法。报告内容由一个XML 文件控制。一个独立的引擎解析这个XML文件,根据解析的结果创建特定的交互部件。改变报告的内容仅需要修改XML文件即可。我也可以轻松的添加新的部 件。源码可以从这里得到:

下载Flex Builder项目

这个SWF同时也演示了一种改进启动时间的技术。我们的Blog系统用起来太痛苦了,我不希望在发表日志的时候上传两个以上的文件,而这篇 报告有成打的图片需要上传。因此,我将这些图片嵌入到SWF中,而不是从外部将它们加载进来。但是,下载这些图片所花费的时间将延迟启动。为了避免这种情 况,我将所有的图片塞进SWF的第三帧,这样Flex就能迅速启动并运行,而这些图片在SWF文件末尾才会被下载。之所以这样做,是因为这些图片并会立刻 被使用。

阅读全文 »

Tags »|

FME 发布音视频使用 FMS 录制

FMS/FCS 无评论 »

FME是adobe公司的免费视频采集软件,可以直接将视频采集卡或摄像头的视频以vb6或h.264的编码方式布到FMS上。比flash player上同码流能得到更优质的视频效果。但FME使用的publish类型只有live,所以FMS不能直接录制,需要在FMS应用下写代码来搞 定。代码如下:

  1. application.onConnect = function(client)
  2. {
  3. application.acceptConnection(client);
  4. client.BeginRecord = function(newName,liveStream)
  5. {
  6. var myStream = Stream.get(newName);
  7. myStream.record();
  8. myStream.play(liveStream,-2,-1,false);
  9. }
  10. client.EndRecord = function(newName)
  11. {
  12. var myStream = Stream.get(newName);
  13. myStream.play(false);
  14. myStream.flush();
  15. }
  16. }
Tags »|