'팁&테크/ActionScript3'에 해당되는 글 24건

  1. 2015.02.05 모바일(앨범)에서 이미지 업로드(CameraRoll사용, 임시파일 생성방식)
  2. 2014.12.23 TextField 에 hand cursor 적용하는 법
  3. 2014.12.03 TextField 에서 라인수 제한하기
  4. 2014.11.25 CellRendrere dispose 하는 방법
  5. 2014.11.24 air 설정디렉토리 운영체제별 경로
  6. 2014.11.10 DisplayObject(Sprite, Bitmap등등)을 회전(rotate)등을 할때 뭉개(Blue)지는 것 막기
  7. 2014.10.29 Slider 콤퍼넌트 트랙과 Thumb 크기 및 위치 변경
  8. 2014.10.29 as3 관련 한줄 메모
  9. 2014.10.17 내장된 폰트의 사용(embeded font)
  10. 2014.10.17 콤보박스 스킨작업 시 주의할 점
2015. 2. 5. 11:22

모바일(앨범)에서 이미지 업로드(CameraRoll사용, 임시파일 생성방식)

임시파일 생성보다는 다이렉트로 올리는게 더 리소스를 작게 사용하나 참고소스로 남겨 둠

받는 쪽에서는 일반적인 파일 업로드 방식(PHP -> $_FILES)으로 사용


package com.utils
{
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.MediaEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.media.CameraRoll;
	import flash.media.MediaPromise;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	import flash.utils.IDataInput;

	public class ImageSelector
	{
		private var cr:CameraRoll;
		private var dataSource:IDataInput;
		private var eventSource:IEventDispatcher;
		private var tempDir:File;
		private var temp:File;
		
		public function ImageSelector()
		{
			cr = new CameraRoll();
		}
		
		public function getImage():void
		{
			if(!CameraRoll.supportsBrowseForImage)
				return;
			
			cr.addEventListener(MediaEvent.SELECT, onImageSelect);
			cr.addEventListener(Event.CANCEL, onBrowseCancel);
			cr.addEventListener(ErrorEvent.ERROR, onMediaError);
			cr.browseForImage();
		}
		
		private function onImageSelect(e:MediaEvent):void
		{
			var imagePromise:MediaPromise = e.data;
			dataSource = imagePromise.open();
			
			if(imagePromise.isAsync)
			{
				eventSource = dataSource as IEventDispatcher;
				eventSource.addEventListener(Event.COMPLETE, onMediaLoaded);
			}
			else
			{
				readMediaData();
			}
		}
		
		private function onMediaLoaded(e:Event):void
		{
			eventSource.removeEventListener(Event.COMPLETE, onMediaLoaded);
			readMediaData();
		}
		
		private function readMediaData():void
		{
			var imageBytes:ByteArray = new ByteArray();
			dataSource.readBytes(imageBytes);
			
			tempDir = File.createTempDirectory();
			
			var now:Date = new Date();
			var filename:String = "IMG" + now.fullYear + now.month + now.hours + now.minutes + now.seconds + ".jpg";
			temp = tempDir.resolvePath(filename);
			
			var stream:FileStream = new FileStream();
			stream.open(temp, FileMode.WRITE);
			stream.writeBytes(imageBytes);
			stream.close();
			
			temp.addEventListener( Event.COMPLETE, uploadComplete );
			temp.addEventListener( IOErrorEvent.IO_ERROR, ioError );
			
			var serverURL:String = "http://업로드할경로";
			if(!serverURL.length)
			{
				removeTempDir();
				return;
			}
			
			try
			{
				temp.upload( new URLRequest( serverURL ) );
			}
			catch( e:Error )
			{
				trace( e );
				removeTempDir();
			}
		}
		
		private function removeTempDir():void
		{
			tempDir.deleteDirectory( true );
			tempDir = null;
			dispose();
		}
		
		private function uploadComplete(e:Event):void
		{
			dispose();
		}
		
		private function ioError(e:IOErrorEvent):void
		{
			dispose();
		}
		
		private function onBrowseCancel(e:Event):void
		{
			cr.removeEventListener(MediaEvent.SELECT, onImageSelect);
			cr.removeEventListener(Event.CANCEL, onBrowseCancel);
			cr.removeEventListener(ErrorEvent.ERROR, onMediaError);
		}
		
		private function onMediaError(e:ErrorEvent):void
		{
			cr.removeEventListener(MediaEvent.SELECT, onImageSelect);
			cr.removeEventListener(Event.CANCEL, onBrowseCancel);
			cr.removeEventListener(ErrorEvent.ERROR, onMediaError);
		}
		
		private function dispose():void
		{
			temp.removeEventListener(Event.COMPLETE, uploadComplete);
			temp.removeEventListener(IOErrorEvent.IO_ERROR, ioError);
			
			cr.removeEventListener(MediaEvent.SELECT, onImageSelect);
			cr.removeEventListener(Event.CANCEL, onBrowseCancel);
			cr.removeEventListener(ErrorEvent.ERROR, onMediaError);
		}
	}
}


2014. 12. 23. 17:36

TextField 에 hand cursor 적용하는 법

TextField 에 직접 마우스커서를 변경할 방법은 없다.


Sprite 를 하나 만들고 TextField 를 추가해서 Sprite 를 버튼 모드로 사용하면 된다.


var tSpr:Sprite = new Sprite();

tSpr.buttonMode = true;

tSpr.mouseChildren = false;

addChild(tSpr);


var t:TextField = new TextField();

tSpr.addChild(t);

2014. 12. 3. 13:19

TextField 에서 라인수 제한하기

로그나 채팅용으로 TextField 를 사용할 경우 크기가 커질 경우 리소스나 처리속도에 문제가 생긴다.


라인수로 일정한 라인 이상이 되면 앞에 들어간 라인을 지우도록 처리하면 된다.


특히 채팅을 만들때 라인별로 TextFormat 이 들어가 있을 경우 

textfield.text = textfield.text.substring(textfield.getLineLength(0));

위와 같이 하면 TextFormat 이 리셋되버리니 절대 사용하면 안된다.


아래와 같이 replaceText를 사용하면 된다.

if(chatText.numLines > 50) { chatText.replaceText(0, chatText.getLineLength(0), ""); } var len:uint = chatText.text.length; chatText.appendText(str); chatText.setTextFormat(textFormat, len, len + str.length);


2014. 11. 25. 16:11

CellRendrere dispose 하는 방법

List 나 DataGrid 등에 CellRenderer 로 사용된 자원을 해제하는 방법이 액션스크립트에는 없다. ㅡㅡ;;


메모리 릭이 생길수 밖에 없는데 사용하지 않게 됬을때 (ex. removeChild) 아래처럼 처리하면 가능하다.


// cell renderers are contained within this sprite var itemHolder:Sprite = (myList.getChildAt(3) as DisplayObjectContainer).getChildAt(0) as Sprite; // dispose each cellRenderer manually for (var i:int = 0; i < itemHolder.numChildren; i++) { (itemHolder.getChildAt(i) as MyCellRenderer).dispose(); } removeChild(myList); //제거하기 전에 위내용을 처리하자!


2014. 11. 24. 15:02

air 설정디렉토리 운영체제별 경로

This info applies to AIR 1.0 and later (ActionScript 3.0)

  • File.applicationStorageDirectory: a storage directory unique to each installed AIR application. This directory is an appropriate place to store dynamic application assets and user preferences. Consider storing large amounts of data elsewhere. On Android and iOS, the application storage directory is removed when the application is uninstalled or the user chooses to clear application data, but this is not the case on other platforms.

  • File.applicationDirectory: the directory where the application is installed (along with any installed assets). On some operating systems, the application is stored in a single package file rather than a physical directory. In this case, the contents may not be accessible using the native path. The application directory is read-only.

  • File.desktopDirectory: the user’s desktop directory. If a platform does not define a desktop directory, another location on the file system is used.

  • File.documentsDirectory: the user’s documents directory. If a platform does not define a documents directory, another location on the file system is used.

  • File.userDirectory: the user directory. If a platform does not define a user directory, another location on the file system is used.

If you specify a publisher ID in the AIR application descriptor, then the publisher ID is appended to the applicationID.

Android

  • File.applicationDirectory (read-only)

    /data/data/

  • File.applicationStorageDirectory

    /data/data/<applicationID>/<filename>/Local Store

  • File.cacheDirectory

    /data/data/<applicationID>/cache

  • File.desktopDirectory

    /mnt/sdcard

  • File.documentsDirectory

    /mnt/sdcard

  • temporary - from File.createTempDirectory() and File.createTempFile()

    /data/data/<applicationID>/cache/FlashTmp.<randomString>

  • File.userDirectory

    /mnt/sdcard

iOS

  • File.applicationDirectory (read-only)

    /var/mobile/Applications/<uid>/<filename>.app

  • File.applicationStorageDirectory

    /var/mobile/Applications/<uid>/Library/Application Support/<applicationID>/Local Store

  • File.cacheDirectory

    /var/mobile/Applications/<uid>/Library/Caches

  • File.desktopDirectory - not accessible

  • File.documentsDirectory

    /var/mobile/Applications/<uid>/Documents

  • temporary - from createTempDirectory() and createTempFile()

    /private/var/mobile/Applications/<uid>/tmp/FlashTmp<randomString>

  • File.userDirectory - not accessible

Linux

  • File.applicationDirectory (read-only)

    /opt/<filename>/share

  • File.applicationStorageDirectory

    /home/<userName>/.appdata/<applicationID>/Local Store

  • File.desktopDirectory

    /home/<userName>/Desktop

  • File.documentsDirectory

    /home/<userName>/Documents

  • temporary - from createTempDirectory() and createTempFile()

    /tmp/FlashTmp.<randomString>

  • File.userDirectory

    /home/<userName>

Mac

  • File.applicationDirectory (read-only)

    /Applications/<filename>.app/Contents/Resources

  • File.applicationStorageDirectory (AIR 3.2 and earlier)

    /Users/<userName>/Library/Preferences/<applicationID>/Local Store

  • File.applicationStorageDirectory (AIR 3.3 and later)

    /Users/<userName>/Library/Application Support/<applicationID>/Local Store

  • File.applicationStorageDirectory (AIR 3.3 and later) sandboxed

    /Users/<userName>/Library/Containers/<bundleID>/Data/Library/Application Support/<applicationID>/Local Store

  • File.cacheDirectory

    /Users/<userName>/Library/Caches

  • File.desktopDirectory

    /Users/<userName>/Desktop

  • File.documentsDirectory

    /Users/<userName>/Documents

  • temporary - from createTempDirectory() and createTempFile()

    /private/var/folders/<userName?>/<randomString>/TemporaryItems/FlashTmp

  • File.userDirectory

    /Users/<userName>

Windows

  • File.applicationDirectory (read-only)

    C:\Program Files\<filename>

  • File.applicationStorageDirectory

    C:\Documents and settings\<userName>\ApplicationData\<applicationID>\Local Store

  • File.cacheDirectory

    C:\Documents and settings\<userName>\Local Settings\Temp

  • File.desktopDirectory

    C:\Documents and settings\<userName>\Desktop

  • File.documentsDirectory

    C:\Documents and Settings\<userName>\My Documents

  • temporary - from createTempDirectory() and createTempFile()

    C:\Documents and Settings\<userName>\Local Settings\Temp\<randomString>.tmp

  • File.userDirectory

    C:\Documents and Settings\<userName>


2014. 11. 10. 17:51

DisplayObject(Sprite, Bitmap등등)을 회전(rotate)등을 할때 뭉개(Blue)지는 것 막기

DisplayObject 를 회전(rotate) 시키면 객체가 2D 에서 3D 객체로 변환이 된다.


3D 객체가 되면 이미지등이 뭉개져 버리는 증상이 생기는데 이 경우에는 아래 처럼 3dMatrix 좌표계(?)를 리셋하고 위치 좌표를 재정의 또는 새로운 좌표계를 할당하고 위치 좌표를 재정의 해주면 된다.


var x:Number = displayObject.x;

var y:Number = displayObject.y;

displayObject.transform.matrix3D = null;

displayObject.x = x;

displayObject.y = y;


또는


var x:Number = displayObject.x;

var y:Number = displayObject.y;

displayObject.transform.matrix = new Matrix();

displayObject.x = x;

displayObject.y = y;

2014. 10. 29. 15:03

Slider 콤퍼넌트 트랙과 Thumb 크기 및 위치 변경

chipSlider = new Slider();

chipSlider.direction = SliderDirection.HORIZONTAL;

chipSlider.width = 100;


var chipSliderTrack:Sprite = Sprite(chipSlider.getChildAt(0)); //트랙의 Sprite

chipSliderTrack.x = 4;

chipSliderTrack.y = 4;

chipSliderTrack.width = 110;

chipSliderTrack.height = 33;


var chipSliderThumb:Sprite = Sprite(chipSlider.getChildAt(1)); //Thumb 의 Sprite

chipSliderThumb.y = 1;

chipSliderThumb.width = 11;

chipSliderThumb.height = 41;


actionPageOnTurn.addChild(chipSlider);

2014. 10. 29. 09:51

as3 관련 한줄 메모

- sprite 에 외곽선 넣기

ui구성시 sprite 크기 및 차지하는 범위를 알려고 할때 쓰면 좋음


var sp:Sprite = new Sprite();

sp.graphics.lineStyle(0,0x555555,0.5);

sp.graphics.drawRect(0,0,sprite폭, sprite높이);


- textfield htmlText로 img 넣을때 주의점

wordwrap = true 를 줘야됨


- 외부이미지를 동적로딩 할때

이미지 데이타를 할당 받고 이미지 크기를 조정해야 됨.

이미지 데이타를 적용하기 전에 미리 크기를 조절하면 이미지가 안보임

2014. 10. 17. 10:22

내장된 폰트의 사용(embeded font)

먼저 폰트를 embed 하는 방법


[Embed(source="경로/폰트.ttf", fontName = "폰트호출명", embedAsCFF="false", mimeType="application/x-font-truetype")]

public static var eFont:Class;



TextFormat 클래스로 사용

var tf:TextFormat = new TextFormat("폰트호출명", .....);


또는 

var tf:TextFormat = new TextFormat();

tf.font = "폰트호출명";



-- 주의 --

내장된 폰트를 사용하기 위해서는 TextFormat를 할당하는 개체에도 내장된 폰트를 사용하게끔 설정해야 된다.

그리고 antiAlias를 ADVANCED로 줘야 그나마 깔끔하게 출력됨


var t:TextField = new TextField();

t.embedFonts = true;

t.antiAliasType = AntiAliasType.ADVANCED;

t.defaultTextFormat = tf;  <- TextFormat 객체


setStyle로 적용할 경우

t.setStyle("textFormat", tf);

t.setStyle("embedFonts", true);


2014. 10. 17. 10:13

콤보박스 스킨작업 시 주의할 점

에어나 플렉스에서 combobox 스킨을 변경해야 하는 경우가 대부분인데.


combobox 는 크게 두가지 combobox + dropdown(list) 로 구성되어 있어 따로 skin 작업을 해줘야 한다.


보통 이미지로 스킨을 입힐꺼기 때문에 bitmap 으로 스킨을 만드는데


var cb:ComboBox = new ComboBox();


//combobox 자체의 스킨

cb.setStyle("upSkin", new Bitmap(...)); //보통상태일때 스킨

cb.setStyle("downSkin", new Bitmap(...)); //클릭한 상태일때 스킨

cb.setStyle("overSkin", new Bitmap(...)); //마우스가 오버상태일때 스킨

cb.setStyle("disabledSkin", new Bitmap(...)); //disable 상태일때 스킨


//dropdown(list)의 스킨

cb.dropdown.setRendererStyle("upSkin", new Bitmap(...));

cb.dropdown.setRendererStyle("downSkin", new Bitmap(...));

cb.dropdown.setRendererStyle("overSkin", new Bitmap(...));

cb.dropdown.setRendererStyle("disabledSkin", new Bitmap(...));

cb.dropdown.setRendererStyle("selectedUpSkin", new Bitmap(...)); //현재 선택된 아이템의 보통상태 스킨

cb.dropdown.setRendererStyle("selectedOverSkin", new Bitmap(...)); //현재 선택된 아이템의 마우스 오버시 상태 스킨

cb.dropdown.setRendererStyle("selectedDownSkin", new Bitmap(...)); //현재 선택된 아이템의 마우스 클릭 시 스킨


문제는 붉은 부분과 같이 dropdown의 스킨을 처리를 할 경우 스크롤을 하다 보면 


"The supplied DisplayObject must be a child of the caller." 오류가 발생하게 된다.


이부분을 해결하기 위해서 아래와 같이 별도의 cellRenderer 를 만들어서 해결해야 한다.


public class ComboBoxRender extends CellRenderer

{

    public function ComboBoxRender()

    {

        super();

        

        this.setStyle("upSkin", new Bitmap(...));

        this.setStyle("overSkin", new Bitmap(...));

        this.setStyle("downSkin", new Bitmap(...));

        this.setStyle("selectedUpSkin", new Bitmap(...));

        this.setStyle("selectedOverSkin", new Bitmap(...));

        this.setStyle("selectedDownSkin", new Bitmap(...));

    }

}


//cellRender 적용

cb.dropdown.setStyle("cellRenderer", CellRenderer);