[카테고리:] AS3

  • Array.length is a read-write property.

    Array.length is a read-write property. I should’ve know it.
    I just thought it was a read-only property. I came to know it reading a copy of EAS3.0.
    Array.length 속성이 리드-라이트 였네요. 이런걸 지금까지 모르고 있었다니…
    당연히 Read-only일 거라고 생각하고 있었는데, EAS3.0을 보다가 알게 되었네요.
    Array.lengthがread-write属性だったんですね。なぜ今まで知らなかったんだろう……
    当然read-onlyだと思っていったのに、EAS3.0を読みながら分かった。

    length property
    length:uint [read-write]

    Language Version : ActionScript 3.0
    Player Version : Flash Player 9

    A non-negative integer specifying the number of elements in the array. This property is automatically updated when new elements are added to the array. When you assign a value to an array element (for example, my_array[index] = value), if index is a number, and index+1 is greater than the length property, the length property is updated to index+1.

    Note: If you assign a value to the length property that is shorter than the existing length, the array will be truncated.

    quote from ActionScript 3.0 Language Reference

    var arr:Array = new Array(0, 1, 2, 3, 4, 5, 6);
    trace(arr);// output 0,1,2,3,4,5,6
    arr.length = 4;
    trace(arr);// output 0,1,2,3
    If the newly assigned length is shorter than the existing value, items whose index is larger than the length will be removed from the array and the array will be shortened to the specified length. In some cases, it is more useful than Array.slice() or Array.splice() methods.
    위와 같이 length에 현재 길이보다 작은 값을 입력하면, length 이후의 아이템들을 제거하고 배열이 입력받은 길이로 줄어들게 됩니다. 경우에 따라서는 Array.slice(), Array.splice() 보다 유용할 것 같네요.
    若し、新しいlengthが現在のlengthより少ないと、それ以後の配列要素は取り去れて、その配列の長さは短くなります。時折Array.slice()やArray.splice()メソッドより便利そうです。
  • Saving an image with AS3 and PHP: 3. ByteArray

    The following ActionScript 3 code is used to save GIF image that is encoded using GIFEncoder. I use GIFEncoder, distributed via ByteArray.org, to encode GIF files.
    다음은 GIFEncoder를 이용하여 인코딩한 GIF 파일을 저장하는 액션스크립트3 코드입니다. GIF 파일을 인코딩하기 위해서, ByteArray.org에서 배포하는 GIFEncoder를 사용하였습니다.
    これはGIFEncoderを使用してGIFファイルを保存するActionScript3のコードです。GIFファイルをエンコードするために、ByteArray.comで配布されているGIFEncoderを使いました。
    // Imports the GIFEndocer class by Thibault Imbert.
    // You can download it from ByteArray.org.
    import org.gif.encoder.GIFEncoder;
    
    var serverPath:String = "/";
    
    // Initializes GIFEncoder
    var myGIFEncoder:GIFEncoder = new GIFEncoder();
    myGIFEncoder.setRepeat(0);
    myGIFEncoder.setDelay (300);
    
    // Initializes an URLLoader object to upload a file stream.
    var ul:URLLoader = new URLLoader();
    ul.addEventListener(Event.COMPLETE, saveDone);
    
    var urh:URLRequestHeader = new URLRequestHeader("Accept","image/gif");
    var BOUNDARY:String = "---------------------------7d76d1b56035e";
    
    /**
     * Starts the gif encoding when clicks on the stage.
     */
    stage.addEventListener(MouseEvent.CLICK, generateGIF);
    function generateGIF(evt:MouseEvent):void{
    	
    	// Starts the gif encoder.
    	myGIFEncoder.start();
    	
    	// Add frame.
    	var bd:BitmapData = new BitmapData(100, 100, false, Math.round(0xFFFFFF*Math.random()));
    	myGIFEncoder.addFrame(bd);
    	
    	// Finishes the gif encoder.
    	myGIFEncoder.finish();
    	
    	// Starts the upload process.
    	uploadGIF();
    	
    }// end generateGIF
    
    /**
     * Generates a file stream and upload it.
     */
    function uploadGIF():void{
    	
    	// Retrieves the file stream from the GIF Encoder.
    	var myGIFStream:ByteArray = myGIFEncoder.stream;
    	var filename:String = "test.gif";
    	
    	// Creates the file header.
    	var formData:String  =  "--" + BOUNDARY + '\r\nContent-Disposition: form-data; name="Filedata"; filename="' + filename + '"\r\nContent-Type: application/octet-stream\r\n\r\n';
    	var formData2:String = "\r\n";
    	formData2 += "--" + BOUNDARY + '\r\nContent-Disposition: form-data; name="Filedata"\r\n\r\nSubmit Query\r\n';
    	formData2 += "--" + BOUNDARY + '--';
    	
    	
    	// Conbines the header and the file stream.
    	var dataArray:ByteArray = new ByteArray();
    	dataArray.writeMultiByte(formData,"ascii");
    	for(var k:uint=0; k
    
    Special thanks to Kim Eung. He devised the draft of the PHP and AS3 codes. Furthermore, he allowed me to open them to the public.
    이 PHP와 AS3 코드의 기틀을 만들고, 이 소스를 공개하는데 흔쾌히 동의하신, 김응 실장님에게 진심으로 감사드립니다.
  • Saving an image with AS3 and PHP: 2. FileReference

    The following code is an ActionScript 3.0 code that uploads files via FileReference.
    다음은 FileReference를 이용하여 파일을 업로드하는 액션스크립트3 코드입니다.
    Sorry, Japanese translation is not yet available.
    var serverPath:String = "/";
    
    // Creates a FileReference object.
    var fr:FileReference = new FileReference();
    var frFilter:FileFilter = new FileFilter("JPGs", "*.jpg");
    
    // Adds events to the FileReference object.
    fr.addEventListener(Event.SELECT, fileSelected);
    fr.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, fileUploaded);
    fr.addEventListener(ProgressEvent.PROGRESS, fileProgress);
    fr.addEventListener(IOErrorEvent.IO_ERROR, errorOccured);
    
    
    /**
     * Executes when a user selects a file to upload.
     */
    function fileSelected(evt:Event):void{
    	
    	// Checks the size of the file.
    	if(fr.size > 200*1024){
    		trace("You can NOT upload an image lagerer than 200KB.");
    	}else{
    		var ur:URLRequest = new URLRequest();
    		ur.url = serverPath + "test/uploadok.php";
    		
    		// Puts newName parameter, to avoid the multi-byte filename problem.
    		var uv:URLVariables = new URLVariables();
    		uv.newName = "upload.jpg";
    		
    		ur.data = uv;
    		
    		// Starts uploading.
    		fr.upload(ur);
    	}// end if else [fr.size]
    	
    }// end fileSelected
    
    
    /**
     * Executes when a file upload is finished.
     */
    function fileUploaded(evt:DataEvent):void{
    	trace(evt.data);
    }// end fileUploaded
    
    /**
     * Executes while uploading a file.
     */
    function fileProgress(evt:ProgressEvent):void{
    	//trace(evt.bytesLoaded + " / " + evt.bytesTotal);
    }// end fileProgress
    
    /**
     * Executes when an IO error occurs.
     */
    function errorOccured(evt:IOErrorEvent):void{
    	trace("IO error has occured.");
    }// end errorOccured
    
    
    /**
     * Shows the file browser when clicks on the stage.
     */
    stage.addEventListener(MouseEvent.MOUSE_DOWN, clicked);
    function clicked(evt:MouseEvent):void{
    	fr.browse([frFilter]);
    }
    In line 27 through 30, I assign newName parameter to an URLVariables object. This is to avoid IO error which occurs if the filename contains 2-byte characters. If you let the serverscript rename the uploaded file, this is not needed.
    27-30번째 줄을 보면, URLVariables 객체에 newName 파라메터를 설정했습니다. 이것은 파일명에 한글과 같은 2바이트 문자가 포함된 경우 서버에서 파일 저장시에 IO 에러가 발생하기 때문에, 이를 피하기 위해서 newName에 별도의 파일명을 저장한 것입니다. 만약 서버측에서 파일명을 변경하도록 구성되어 있다면, 이 부분은 필요 없습니다.
    var uv:URLVariables = new URLVariables();
    uv.newName = "upload.jpg";
    
    ur.data = uv;
  • Saving an image with AS3 and PHP: 1. PHP

    The following PHP code is the code to save an image, which is uploaded using FileReference or is encoded using ByteArray in a Flash movie. The uploadok.php file can handle all the files, uploaded using FileReference, ByteArray or a file form in an HTML document.
    다음 코드는 플래시에서 FileReference를 사용한 업로드 또는 ByteArray로 인코딩된 파일을 저장하기 위한 PHP 코드입니다. 이 uploadok.php 파일 하나로 플래시의 FileReference, ByteArray는 물론 HTML문서의 파일 양식을 통한 업로드도 모두 처리가 가능합니다.
    Sorry, Japanese translation is not yet available.
    Special thanks to Kim Eung. He devised the draft of the PHP and AS3 codes. Furthermore, he allowed me to open them to the public.
    이 PHP와 AS3 코드의 기틀을 만들고, 이 소스를 공개하는데 흔쾌히 동의하신, 김응 실장님에게 진심으로 감사드립니다.
  • AddedToStage event object and root, parent.

    In AS3, There are times that you can not use root or parent properties on a display object. It is because root and parent properties are set to null, unless they are not added to the stage. So, an error occurs when you try to use root or parent properties in the constructor of an class. To avoid this problem, use addedToStage event object, and run codes after a display object was added to the display list.
    AS3의 디스플레이 오브젝트에서 root 또는 parent 속성을 참조하지 못하는 경우가 종종 있습니다. 이는 root 및 parent 속성은 디스플레이 오브젝트가 스테이지에 애드되지 않으면 null 값을 가지기 때문입니다. 그러므로 클래스 컨스트럭터에서 root 또는 parent를 참조하려 할 때 에러가 발생하는 것입니다. 이를 해결하기 위해서 addedToStage 이벤트 오브젝트를 사용하여, 디스플레이 오브젝트가 디스플레이 리스트에 추가되었을 때 필요한 코드를 실행하도록 하면 됩니다.
    AS3で、ディスプレーオブジェクトがrootやparentプロパ ティを参照できない時があります。それは、ディスプレーオブジェクトがステ―ジに追加されていないと、rootとparentプロパ ティはnullに設定されると言うわけです。だから、クラスのコンストラクタの中でrootやparentプロパ ティ参照しようとする時、エラーが発生するのです。このエラーを回避するために、addedToStageイベントオブジェクトを使用し、ディスプレーオブジェクトがディスプレーリストに追加された時、コードを実行します。

    root property
    root:DisplayObject [read-only]

    …… The root property is set to null for any display object that has not been added to the display list, unless it has been added to a display object container that is off the display list but that is a child of the top-most display object in a loaded SWF file.

    quote from ActionScript 3.0 Language and Components Reference

    The following codes are the codes that I use frequently. I choose _root and _parent keywords that are not used in AS3.
    다음 코드는 제가 자주 사용하는 코드로, AS3에서는 사용되지 않는 _root, _parent 키워드를 사용합니다.
    下のコードは私がよく使うこーどで、私はAS3では使わない_rootと_parentキーワードを選びました。
    package{
    	
    	import	flash.display.MovieClip;
    	import	flash.events.Event;// added on 2011.03.24
    	
    	public class SomeClass extends MovieClip{
    		
    		private var _root:MovieClip;
    		private var _parent:MovieClip;
    		
    		public function SomeClass(){
    			
    			addEventListener(Event.ADDED_TO_STAGE, initialize);
    			
    		}// end SomeClass constructor
    		
    		
    		/**
    		 * Initializes the SomeClass, when an instance is added to the display list
    		 */
    		private function initialize(evt:Event):void{
    			
    			removeEventListener(Event.ADDED_TO_STAGE, initialize);
    			
    			_root = root as MovieClip;
    			_parent = parent as MovieClip;
    			
    		}// end initialize
    		
    	}// end SomeClass definition
    	
    }// end package