2013年5月31日 星期五

[Flash] Component Related

Convert symbol to class (and use its members)
1. right click to convert primitives to a symbol
2. check "Export for ActionScript"
3. give instance name for the symbol (to be able to be accessed from parent symbol)

Default Symbol Class : MovieClip

enable/disable mouse control on object : .mouseEnabled, .mouseChildren

Make sure no components on the component that has mouseEventListener, otherwise mouseEvent won't work

2013年5月29日 星期三

[Flash] use Flash in Flex

http://vimeo.com/3484200
http://vimeo.com/3484055

[Flex] Popup Window

http://blog.flexexamples.com/2009/10/23/displaying-a-popup-spark-titlewindow-container-in-flex-4/

Window Component:
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/10/23/displaying-a-popup-spark-titlewindow-container-in-flex-4/ -->
<s:Application name="Spark_TitleWindow_test"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/halo">
    <s:controlBarContent>
        <s:Button id="btn"
                label="Show TitleWindow"
                click="btn_click(event);" />
    </s:controlBarContent>
 
    <fx:Script>
        <![CDATA[
            import comps.MyTitleWindow;
            import mx.managers.PopUpManager;
 
            protected function btn_click(evt:MouseEvent):void {
                var ttlWndw:MyTitleWindow = PopUpManager.createPopUp(this, MyTitleWindow, true) as MyTitleWindow;
                PopUpManager.centerPopUp(ttlWndw);
            }
        ]]>
    </fx:Script>
 
</s:Application>

Main
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/10/23/displaying-a-popup-spark-titlewindow-container-in-flex-4/ -->
<s:TitleWindow name="MyTitleWindow"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/halo"
        title="Spark TitleWindow title"
        width="300" height="200"
        close="ttlWndw_close(event);">
 
    <fx:Script>
        <![CDATA[
            import mx.core.IFlexDisplayObject;
            import mx.events.CloseEvent;
            import mx.managers.PopUpManager;
 
            protected function ttlWndw_close(evt:CloseEvent):void {
                PopUpManager.removePopUp(evt.currentTarget as IFlexDisplayObject);
            }
        ]]>
    </fx:Script>
 
</s:TitleWindow>

[Flex] Misc

Some libraries will not be available under different environments (WebApp or Desktop (AIR))

use package in MXML:
<s:Application
xmlns:namespace_name="package"
e.g.: xmlns:file="flash.filesystem.*"
then in <fx:Declaration>: <file:File id="id"/>

Coding conventions:
http://sourceforge.net/adobe/flexsdk/wiki/Coding%20Conventions/
public static const AAA_BBB:String = "value"

set lib (source path): set the parent directory of lib package

show Sprite (include bitmapData )on MXML: use UIComponent:
var ui:UIComponent = new UIComponent;
ui.addChild(sprite);
group.addElement(ui);  //group: spark group

[Flex] Keys

[Flex]
http://dispatchevent.org/mims/flexbuilder-keyboard-shortcuts/
Editing:
Shift+direction keys: select text

text selected->(ctrl+alt)+up/down: copy&paste selected text

Other:
F3/ Ctrl+Mouse Click: Open Declaration

Ctrl+Q: go to last modified line

Ctrl+L : go to one specific lime

Ctrl+Shift+D: ASDoc style comment

Ctrl+Shift+T: search class

Alt + <-, -> : last cursor

[Flash]
Ctrl+Shift+V: paste at the same position

[Flex] Slice Image

package utils
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.errors.IllegalOperationError;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.net.registerClassAlias;
import spark.primitives.BitmapImage;
public class ImageSlicer
{
/**
* Creates a new ImageSlicer
*
* @constructor
* @throws IllegalOperationError
*/
public function ImageSlicer() {
throw new IllegalOperationError('ImageSlicer cannot be instantiated.');
}
public static function sliceImageWithFixedSliceSize(image:BitmapData,sliceWidth:uint,sliceHeight:uint):Array
{

var iWidth:Number = image. width;
var iHeight:Number = image.height;
var testMod:Boolean;
testMod=((iWidth%sliceWidth)>0)?true:false;
var numCols:uint=iWidth/sliceWidth+testMod;

testMod=((iHeight%sliceHeight)>0)?true:false;
var numRows:uint=iHeight/sliceHeight+testMod;

var iArray:Array = new Array();

var rectangle:Rectangle=new Rectangle();
var bitmap:Bitmap;
var bData:BitmapData;
for( var rowIdx:int = 0; rowIdx < numRows; rowIdx++ ) {
iArray[rowIdx] = new Array();
for( var colIdx:int = 0; colIdx < numCols; colIdx++ ) {
bData = new BitmapData( sliceWidth, sliceHeight, true, 0x00000000 );
rectangle = new Rectangle( colIdx * sliceWidth, rowIdx * sliceHeight, sliceWidth, sliceHeight );
bData.copyPixels( image, rectangle, new Point( 0, 0 ) );
bitmap = new Bitmap( bData );
iArray[rowIdx][colIdx] = bitmap;
}
}

return iArray;
}
}
}

[Flex] Add Bitmap elements in Group

<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"
  xmlns:ns1="*"
  xmlns:net="flash.net.*"
  minWidth="955" minHeight="600"
  width="1024" height="768">
<fx:Script>
<![CDATA[      
import mx.controls.Alert;
import mx.controls.Image;

                       [Embed(source="pic1.jpg")]
[Bindable]
public var imgCls:Class;

                       private function addGroup(event:MouseEvent):void
{
img.source=imgCls;
var bitmapData:BitmapData=img.bitmapData;

var group:Group=new Group();
testGroup.gap=70;
var lay:VerticalLayout=new VerticalLayout();
lay.gap=50;
group.layout=lay;
var uic:UIComponent;
var btnn:Button;
for(var i:uint=0;i<3;i++)
{
var bitmap:Bitmap=new Bitmap(bitmapData);
var imgg:mx.controls.Image=new mx.controls.Image();
imgg.source=bitmap;
group.addElement(imgg);
}
testGroup.addElement(group);
}
                ]]>
</fx:Script>

              <s:VGroup>


<s:HGroup id="testGroup">

</s:HGroup>
<s:VGroup>
<s:Button label="btn" id="btn" click="addGroup(event)"/>
<s:Image id="img"/>
</s:VGroup>
</s:VGroup>

</s:Application>

[Flex] state

<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"
  xmlns:ns1="*"
  xmlns:net="flash.net.*"
  minWidth="955" minHeight="600"
  width="1024" height="768">

        <s:states>
 <s:State name="default"/>
 <s:State name="other"/>
</s:states>

<fx:Script>
<![CDATA[

                       private function toggleState(event:MouseEvent):void
{
switch (currentState) {
case "other":
currentState = "default";
break;
case "default":
currentState = "other";
break;
}
}
               ]]>
</fx:Script>

       <s:VGroup>
       <s:Button label="Change State" id="btnChangeState" click="toggleState(event)"/>
       <s:Button label="in default" includeIn="default"/>
       <s:Button label="in other" includeIn="other"/>
       </s:VGroup>
</s:Application>

[Flex] Save File

Save File in Adobe Flex -AIR

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:WindowedApplication xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” creationComplete=”onCreate(event)”><mx:Script><![CDATA[import flash.filesystem.FileMode;import flash.filesystem.FileStream;import flash.filesystem.File;
private
 function onCreate(e:Event):
void
{

var file:File = File.desktopDirectory; //Set the Directory location to Desktop
file = file.resolvePath(
"test.txt"); //File Name
var
 fileStream:FileStream = new
 FileStream();   // Create new FileStream to Perform Read or Write
fileStream.open(file, FileMode.WRITE); // Open file in WRITE Mode
fileStream.writeUTFBytes(
"Hello World"); //Write Hello World into test.txt 
fileStream.close(); //Close the File Stream
}

]]>
</mx:Script>
</mx:WindowedApplication>

This code creates a file named test.txt with content “Hello World” in desktop folder.
The desktopDirectory property provides a way to reference the desktop directory that works across platforms. If you set a File object to reference the desktop directory using the nativePath or url property, it will only work on the platform for which that path is valid Similarly documentDirectory /applicationStorageDirectory /applicationDirectory can be used to represent the folder.
var file:File = new File();
file = file.resolvePath(
“c:\\test.txt”);



http://www.flex-blog.com/save-data-to-file-system-with-air-in-flex-4/
 private function save():void
            {
                // Create file object
                file = File.documentsDirectory.resolvePath(directory + "\\" + fileName);
                // FileStream for writing the file
                fileStream = new FileStream();
                // Open the file in write mode
                fileStream.open(file, FileMode.WRITE);
                // Write the ArrayCollection object of persons to the file
                fileStream.writeObject(persons);
                // Close FileStream
                fileStream.close();
            }
            
            private function read():void
            {
                // Get hte correct path
                file = File.documentsDirectory.resolvePath(directory + "\\" + fileName);
                
                // read the file if it exists
                if(file.exists)
                {
                    // FileStream for reading the file
                    fileStream = new FileStream();
                    // Open the file in read mode
                    fileStream.open(file, FileMode.READ);
                    // Read the ArrayCollection object of persons from the file
                    persons = fileStream.readObject() as ArrayCollection;
                    // Close the FileStream
                    fileStream.close();
                }
                else
                {
                    // some sample data + save if file does not exist
                    persons = new ArrayCollection();
                    var person:Object = new Object();
                    person.firstName = "John";
                    person.lastName = "Doe";
                    persons.addItem(person);
                    
                    person = new Object();
                    person.firstName = "Peter";
                    person.lastName = "Pan";
                    persons.addItem(person);
                    
                    person = new Object();
                    person.firstName = "Captain";
                    person.lastName = "Hook";
                    persons.addItem(person);
                    save();
                }
            }

2013年5月26日 星期日

Flex Note 1

tags:
<s:  spark

add class instance: use mxml component

event type: bubbles,cancelable,currentTarget,eventPhase,Target,Type

Interface:
package oreilly.cookbook {
public interface IDataInterface {
function set dataType(value:Object):void;
function get dataType():Object;
function update():Boolean;
function write():Boolean;
function readData():Object;
}
}

public class ClientData extends EventDispatcher implements IDataInterface {

Interface in XML:
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml"
width="400" height="300" implements= "IDataInterface">

Containers : MX, Spark

Group: addElement, removeElement, swapElement

binding: event-based: sync event to objects that are affected
binding: for pass data [Bindable] public var aaa;
Class with binding: must implement IEventDispatcher

bind in MXML: {} or <fx:Binding>
<fx:Binding source="nameInput.text" destination="nameOutput.text" />

bind function:<s:RichText text="{function(arg.text )}" />

in actionscript :Use the mx.utils.binding.BindingUtils class to create mx.utils.binding.Change
Watcher objects.

custom bind
[Bindable(event="fnChanged")]


Browser: navigateToURL( new URLRequest( newUrl.text ),
target.selectedItem as String );
<mx:TextInput id="newUrl"
top="10" left="10" right="10"
text="http://www.oreilly.com/" />
<mx:ComboBox id="target"
top="40" left="10"
dataProvider="{ [ '_blank', '_self' ] }" />

use flashvars into <embed> tag

AS call javascript: ExternalInterface.call("JSFunc");

change html title: BrowserManager.setTitle();
ParseURL: URLUtil

Data from URL into Flex control: BrowserManager.addEventListener(BrowserChangeEvent.BROWSER_URL_CHANGE, func);

control visible contents of Flex by URL param

2013年5月24日 星期五

Action Script Advance Function 1

stage: root of display list hierachy
Display object containers:an object that is capable of containing child display
objects,  Sprite, MovieClip, and Shape,  a display object container is
removed from the display list, all its children are removed as well

Display objects: a visual element,  Some classes function as both display
objects and display object containers

Display Object List (Children)
Child 0 is the deepest (will be occluded by other objects)
Children indices must be continuous :0,2 is not allowed, must be 0,1,2
addChild(Object_Name)//equals to stage.addChild(Object_name)
addChildAt(Object_Name, index) other objects indices will shift by 1

reparenting
container1.addChild(Object1);
container2.addChild(Object2);
now container1 does not have Object1

removeChild(Object_name);
removeChildAt(index);

numChildren:check number of Children

ascb.util.DisplayObjectUtilities class:

DisplayObjectUtilities.removeAllChildren( this );

Move Object:
setChildIndex(Object_name,index);

getChildAt(index)

load resource: 6.6 (Loader class)

mouse 6.8

Filter: image filter (e.g. convolution filter)


String:

var attendance:int = 24;
// Results in a single value of "There are 24 people"
var output:String = "There are " + attendance + " people";


var first:int = 24;
var second:int = 42;
// Results in a string value of "2442"
var result:String = "" + first + second;


var first:int = 24;
var second:int = 42;
// Results in a string value of "66"
var result:String = first + second + "";


var first:int = 24;
var second:int = 42;
var third:int = 21;
// Results in a string value of "6621"
var result:String = first + second + String( third );


var first:int = 24;
var second:int = 42;
var third:int = 21;
// Results in a string value of "244221"
var result:String = first.toString( ) + second + third;


var first:int = 24;
var second:int = 42;
// Results in "There are 66 people"
var result:String = "There are " + ( first + second ) + " people";

new line,tab... 12.3

Timer:
var timer:Timer=new Timer(1000); exec every 1 second

timer.addEventListener(TimerEvent.TIMER, onTimer); onTimer: function name

function onTimer(event:TimerEvent):void {
trace("on timer");
}
timer.start( );


Sound:

_sound = new Sound(new URLRequest("song.mp3"));
_sound.play(delay, loop_times );

buffer sound 5 second

var request:URLRequest = new URLRequest("song.mp3");
var buffer:SoundLoaderContext = new SoundLoaderContext(5000);
_sound = new Sound(request, buffer);
_sound.play( );

SoundChannel->addEventListener(Event.SOUND_COMPLETE,onComplete); //handle sound finish event

Sound.length, Sound.position

SoundChannel.leftPeak/rightPeak :control volume

SoundTransform.volume=0.0~1.0
SoundTransform.pan=-1.0~1.0 (left to right)








2013年5月23日 星期四

Flash Builder Note

Flash set local resource file: File->Publish Setting->Wrench on top left->Browse Source Path
Flex set local resource file: right click on Project name->Properties->Flex Build Path->Source Path(tag)->Browse Source Path

Action Script Basic

is: check if an object is subclass of a class
as: convert subclass instance to super class

package: group of classes (as path)
e.g. : package aaa.bbb{
public class ClassName{
}
}

scope: private, protected, public, internal(classes within the same package can access)

override a function:
e.g. override public function funtionName:returnType{
}

scale movie: action script 3.0 3.6
change alignment 3.7
hide flash player menu items 3.8

allow .swf from other server: 3.12
use .xml to be a policy file:
e.g.
<?xml version="1.0"?>
<!-- http://www.mydomain.com/crossdomain.xml -->
<cross-domain-policy>
<allow-access-from domain="www.otherdomain.com" />
<allow-access-from domain="*.adobe.com" />
<allow-access-from domain="123.45.67.89" />
</cross-domain-policy>
call the policy file:flash.system.Security.loadPolicyFile( )

trace parseInt("103",2); use binary to show 103

String compare
var str:String="1";
var num:uint=1;
trace(str==num); //compile error (if strict mode)
trace(this["str"]==this["num"]);//true
trace(this["str"]===this["num"]);//false

use math function :Math.XX e.g. Math.PI, Math.round();
also check NumberUtilities

Number Format: 4.4,4.5,4.6

addChild(instance name) to show class instance
be sure to release resource of objects (aaa.destroy(); aaa=null;)

Array:
Integer-indexed
Associative array : use keys
var array:Array=new Array();
var array:Array=["a", 2, true, new Object()];
items[4] = "apples";
trace(items[4]); // Displays: apples


var array:Array = new Array();
array.push("val 1", "val 2"); //add at the end
can use Array.pop();


var letters:Array = ["a", "b", "c"];
letters[5] = "f"; =>["a", "b", "c", undefined, undefined, "f"]//(==undefined) is ok

letters.unshift("z"); //add at the begining

length is supported


find elements in array

var letters:Array = ["a", "b", "c", "d", "a", "b", "c", "d"];
trace(ArrayUtilities.findMatchIndices(letters, "b"));
// Displays: 1,5



var words:Array = ["bicycle", "baseball", "mat", "board"];
trace(ArrayUtilities.findMatchIndices(words, "b", true));
// Displays: 0,1,3

findLastMatchIndex( )

Remove elements:
splice()//remove element in middle splice(start pos, num elements to delete)
pop()//remove last
shift()//remove first

var deleted:Array = letters.splice(0, 2);

insert element:

var letters:Array = ["a", "b", "c", "d"];
// Insert three string values ("one", "two", and "three")
// starting at index 1.
letters.splice(1, 0, "r", "s", "t");
// letters now contains seven elements:
// "a", "r", "s", "t", "b", "c", and "d".

//delete and insert together

var letters:Array = ["a", "b", "c", "d"];
// Remove two elements and insert three more
// into letters starting at index 1.
letters.splice(1, 2, "r", "s", "t");
// myArray now contains five elements:
// "a", "r", "s", "t", and "d".

String to Array

var list:String = "Peter Piper picked a peck of pickled peppers";
// Split the string using the space as the delimiter. This puts
// each word into an element of the new array, words.
var words:Array = list.split(" ");

Array to String:

var letters:Array = ["a", "b", "c"];
trace(letters.join("|")); // Displays: a|b|c

copy array:

var letters:Array = ["a", "b", "c"];
// Create an independent copy of letters using concat( ),
// which returns a new array.
var newLetters:Array = letters.concat( );
// Both arrays contain the same values, as expected.
trace(letters); // Displays: "a,b,c"
trace(newLetters); // Displays: "a,b,c"

letters = ["d", "e", "f"];
// Unlike preceding examples, the arrays are independent.
trace(letters); // Displays: "d,e,f"
trace(newLetters); // Displays: "a,b,c"
//NOT REFERENCE

if multi dimention array: concat is REFERENCED, use duplicated:

var coordinates:Array = new Array( );
for(var i:int = 0; i < 4; i++) {
coordinates[i] = new Array( );
for(var j:int = 0; j < 4; j++) {
coordinates[i].push(String(i) + "," + String(j));
}
}
// Duplicate coordinates. Cast the result as an array.
var newCoordinates:Array = ArrayUtilities.duplicate(coordinates, true) as Array;

sort()/reverse() is supported
ArrayUtilities.min( ) and ArrayUtilities.max( )
ArrayUtilities.equals(letters1, letters2)

Associate Array (with Keys)

var memebers:Object = {scribe: "Franklin",
chairperson: "Gina",
treasurer: "Sindhu"};


var members:Object = new Object( );
members.scribe = "Franklin";
members.chairperson = "Gina";
members.treasurer = "Sindhu";

trace(members.scribe); // Displays: Franklin
trace(members["scribe"]); // Displays: Franklin


var members:Object = new Object();
members.councilperson1 = "Beatrice";
members.councilperson2 = "Danny";
members.councilperson3 = "Vladamir";
for (var i:int = 1; i <= 3; i++) {
trace(members["councilperson" + i];
}


for (var sRole:String in members) {
// Displays:
// treasurer: Sindhu
// chairperson: Gina
// scribe: Franklin
trace(sRole + ": " + members[sRole]);
}