Mostrando las entradas con la etiqueta Flex Novatos. Mostrar todas las entradas
Mostrando las entradas con la etiqueta Flex Novatos. Mostrar todas las entradas

jueves, 15 de julio de 2010

SkinnableComponent Skin, Dynamic Change - Flex 4

Ejemplo:
Muchas veces necesitamos un component que se comporte como queramos y eso lo podiamos hacer perfectamente con flex 3, pero cuando hablamos de que se vea como queramos ya era otro cuento, teníamos que dibujar dentro de nuestro component o simplemente dibujaba nuestro Nuevo component en flash e importarlo desde flash a flex usando flex kid component.

Con el nuevo framework de flex, separaron lo que es la parte grafica de los componentes de la parte funcional del mismo. Esto quiere decir, que podemos hacer una clase para hacer que se comporte como queramos y luego hacer otra clase para crear como queremos que se vea.

Este diagrama de arquitectura nos dará una idea a que nos estamos enfrentando ahora en comparación con flex 3





Los componentes sigues extendiendo de UIComponente pero ahora tienen un clase llamada SkinnableComponent de este lado podemos programar todo lo que queremos que nuestro componente haga, y del lado de la interfaz nos crean lo que es la clase skin con esta clase podemos renderizar cualquier componente, existen skins ya prediseñados pero si queremos hacer uno por nuestra cuenta desde cero, extenderemos de skin class.

También tenemos el diagrama del ciclo de vida de los skin:



(Esta Imagen fue sacada de http://opensource.adobe.com/wiki/display/flexsdk/Spark+Skinning)


Tenemos varios métodos que podemos sobre escribir para poder darle muchas más funcionalidades a nuestros diseños, no solo para decorar sino para crear efectos interesantes.

miércoles, 7 de abril de 2010

Communications between two Local Flex Apps - Comicacion entre dos Apps de Flex Locales


Translation:

Algunas veces queremos comunicar dos aplicaciones de Flex o Flash que se encuentran en la misma página, y no vemos la manera de hacerlo.

ActionScript tiene una clase, que nos permite hacer esto sin mucho esfuerzo. Esta clase está ubicada en flash.net. LocalConnection.

Como todo principio de Cliente servidor, una aplicación tiene que escuchar y la otra tiene que ver si hay alguien escuchando.

Veamos el primer código donde vemos la aplicación que escucha, le colocaremos un nombre a la conexión llamada myConnection:
Sometimes we want to communicate two Flex or Flash applications that are on the same page, and do not see how.

ActionScript has a class, allowing us to do so without much effort. This class is located at flash.net. LocalConnection.

The idea is like a client server connection, an application needs to listen and the other has to see if anyone is listening.

Let us first see the application code where you hear, we will place a name to the connection called myConnection:
<?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" minWidth="500" minHeight="300"
      applicationComplete="applicationCompleteHandler(event)" viewSourceURL="srcview/index.html">
 

 
 <fx:Script>
  <![CDATA[
   import mx.collections.ArrayCollection;
   import mx.controls.Alert;
   import mx.events.FlexEvent;
   
   private const connection:LocalConnection = new LocalConnection();
[Bindable] private var   data:ArrayCollection = new ArrayCollection();
   
   protected function applicationCompleteHandler(event:FlexEvent):void
   {
    // TODO Auto-generated method stub
    data.addItem("Application Complete Handler");
    connection.client = this;
    connection.connect("myConnection");
    data.addItem("The Client es THE APP, The name is myConnection");
   }
   
   public function colorBackground(sendedColor:uint):void
   {
    data.addItem("colorBackground Function");
    try
    {
     remoteColor.setStyle("backgroundColor",sendedColor);
     data.addItem("Recived Color in UInt -> "+ sendedColor);
    }
    catch (error:ArgumentError)
    {
     Alert.show("Error trying to connect to LocalConnection.");
    }
   } 
   
  ]]>
 </fx:Script>
 
 <fx:Declarations>
  <!-- Place non-visual elements (e.g., services, value objects) here -->
 </fx:Declarations>
 
 <s:VGroup height="100%" width="100%" 
     x="0" y="0" 
     paddingLeft="20" paddingRight="20" paddingTop="20" paddingBottom="20" 
     horizontalAlign="center">
  <s:Panel id="remoteColor" 
     width="250" height="100" 
     title="Remote Background Color" >
  </s:Panel>
  <s:Panel width="100%" height="100%" 
     title="Console">
   <s:List id="console" 
     width="100%" height="100%" 
     x="0" y="0"
     dataProvider="{data}"></s:List>
  </s:Panel>
 </s:VGroup>
</s:Application>

Ahora veamos la segundo aplicación la cual envía un mensaje a myConnection buscando una función llamada colorBackground y le pasa como parámetro el Color Seleccionado:
Now for the second application which sends a message looking for a function called myConnection colorBackground and passes as parameters the Selected Color:
<?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" 
      minWidth="500" minHeight="300"
      applicationComplete="applicationCompleteHandler(event)" viewSourceURL="srcview/index.html">
 
 <fx:Script>
  <![CDATA[
   import mx.collections.ArrayCollection;
   import mx.controls.Alert;
   import mx.events.ColorPickerEvent;
   import mx.events.FlexEvent;
   
   private const connection:LocalConnection = new LocalConnection();
[Bindable] private var   data:ArrayCollection = new ArrayCollection();
   protected function applicationCompleteHandler(event:FlexEvent):void
   {
    // TODO Auto-generated method stub
    data.addItem("Application Complete Handler");
    connection.addEventListener(StatusEvent.STATUS, connectionStatusHandler);
    data.addItem("Add Listener Status to the Connection");
   }
   
   private function connectionStatusHandler(event:StatusEvent):void
   {
    data.addItem("Connection Status Handler");
    switch (event.level)
    {
     case "status":
      trace("Use of LocalConnection.send() succeeded");
      break;
     case "error":
      Alert.show(
       "The LocalConnection.send() call failed: "
       + event.code + "\n"
       + event.toString() );
      break;
    }
    data.addItem("Status -> "+ event.level );
   }
   
   protected function sendColorHandler(event:ColorPickerEvent):void
   {
    // TODO Auto-generated method stub
    data.addItem("Send Color Handler");
    connection.send("myConnection", "colorBackground", event.color);
    data.addItem("Color Sending in UInt -> " + event.color);
   }
  ]]>
 </fx:Script>
 
 <fx:Declarations>
  <!-- Place non-visual elements (e.g., services, value objects) here -->
 </fx:Declarations>
 <s:VGroup x="0" y="0" 
     width="100%" height="100%" 
     paddingLeft="20" paddingRight="20" paddingTop="20" paddingBottom="20" 
     horizontalAlign="center">
  <mx:ColorPicker change="sendColorHandler(event)"/>
  <s:Panel width="100%" height="100%" 
     title="Console">
   <s:List id="console" 
     x="0" y="0" 
     width="100%" height="100%"
     dataProvider="{data}"></s:List>
  </s:Panel>
 </s:VGroup>
</s:Application>


Los archivos pueden Descargarlos arriba de cada ejemplo.
The files can be downloaded above each example.

Ejemplo Uno - Recive el mensaje:
Example One - The message receiver:

Ver y Descargar Archivo del App 1:
View Source and Download Files of the App 1:


Ejemplo Dos - Envia el Mensaje:
Example Two - Sends the Message:

Ver y Descargar Archivo del App 2:
View Source and Download Files of the App 2:

viernes, 2 de abril de 2010

Cryptography in Flex - Encriptar en Flex - Flex 4


Translation:


Siempre necesitamos usar algún tipo de seguridad, para garantizar a nuestros clientes finales, la seguridad, valga la redundancia, de sus datos. Es por eso que cada ves que vamos a usar un Login o algún texto que necesite de algún tipo de Ofuscamiento, recurrimos a los que son algoritmos de Encriptación.

Flex tiene una librería para encriptar de forma muy sencilla y brinda varios algoritmos, logrando así nuestro objetivo, asegurarnos que nadie tenga la clave o texto de viaje por la red y pueda leerlo o al menos leerlo de forma inmediata.

Aquí les dejo el link para que se bajen la librería para ActionScript, as3corelib Link.

Y aquí le dejos solo la clase donde se ve mejor la implementación, de igual forma al final del texto están todas las clases y archivos del ejemplo, para verlos o descargarlos.
We always need to use some type of security to ensure our end, safety, despite the redundancy of your data. That's why every time we use a login or some text that needs some kind of obfuscation, we turn to those who are encryption algorithms.

Flex is a library for a simple way to encrypt and provides several algorithms, thus achieving our goal, to make sure that no one has the key or text traveling through the network and can read or at least read it immediately.

Here is the link to get off the library for ActionScript, as3corelib Link .

I will leave the most important class, so you can see who is implemented and you can see all the classes and download them at the end of this post.
package com.developyourdream.vo
{
 import com.adobe.crypto.MD5;
 import com.adobe.crypto.SHA1;
 import com.adobe.crypto.SHA224;
 import com.adobe.crypto.SHA256;
 import com.adobe.crypto.WSSEUsernameToken;
 import flash.utils.ByteArray;
[Bindable]
 public class LoginVO
 {
  public function LoginVO()
  {
  }
  private var _username:String;
  private var _password:String;
  private var _cryptoDetail:PasswordVO;
  private var _passwordByteArray:ByteArray;
  
  public function get username():String{
   return _username;
  }
  public function set username(value:String):void{
   _username = value;
  }
  public function get cryptoDetail():PasswordVO{
   return _cryptoDetail;
  }
  public function get password():String{
   return _password;
  }
  public function set password(value:String):void{
   _password = value;
   
   _cryptoDetail = new PasswordVO;
   
   _passwordByteArray = byteArrayTrasform(value);
   
   _cryptoDetail.originalByteArrayPassword = byteArrayToString(_passwordByteArray);
   
   _cryptoDetail.md5   = MD5.hash(_password);
   
   _cryptoDetail.sha1   = SHA1.hash(_password); 
   _cryptoDetail.sha1_base64 = SHA1.hashToBase64(_password); 
   _cryptoDetail.sha1_Bytes = SHA1.hashBytes(_passwordByteArray);
   
   _cryptoDetail.sha224  = SHA224.hash(_password); 
   _cryptoDetail.sha224_base64 = SHA224.hashToBase64(_password); 
   _cryptoDetail.sha224_Bytes = SHA224.hashBytes(_passwordByteArray);
   
   _cryptoDetail.sha256  = SHA256.hash(_password); 
   _cryptoDetail.sha256_base64 = SHA256.hashToBase64(_password); 
   _cryptoDetail.sha256_Bytes = SHA256.hashBytes(_passwordByteArray);
   
   _cryptoDetail.token = WSSEUsernameToken.getUsernameToken(_username,_password);
   
  }
  /*OTHER FUNCTIONS*/
  private function byteArrayTrasform(value:String):ByteArray
  {
   var _auxByteArray:ByteArray;
   _auxByteArray = new ByteArray();
   _auxByteArray.writeMultiByte(value,"utf-8");
   return _auxByteArray;
  }
  private function byteArrayToString(byteArray:ByteArray):String
  {
   byteArray.position = 0;
   var str:String = "";
   while(byteArray.position != byteArray.length - 1)
   {
    str += byteArray.readByte().toString(16).toUpperCase()+" ";
   }
   return str;
  } 
 }
}

Ejemplo:
Example:
Ver y Descargar Archivo:
View Source and Download Files:

martes, 4 de agosto de 2009

Trace a Particle - Dibujar el camino de una Particula - Flex 3

Translation:

En este ejemplo podemos seguir la trayectoria de una animación en este caso una particular basada en formulas matemáticas. El seguir la trayectoria nos puede brindar información de donde estuvo una partícula o donde podrá estar en el futuro en caso de que sea una función cíclica.
This is an example of how we can trace an animation based in a Mathematical formula. The trace can give us information of the particle was in the past and if it’s a Cycle function were its going to be in the future.


En este caso usamos la fórmula para métrica del circulo, usando el sin y cos y colocamos variables dentro de la formula. La formula básica para la X y la Y es la siguiente:

X = sin( angle )* radius + initialPositionInX;
Y = cos( angle )* radius + initialPositionInY;

Para que podamos apreciar una animación necesitamos que el ángulo sea variable y un contador, también podemos colocar una velocidad a ese ángulo para que vaya más rápido.
Las formulas nos quedarían expresadas de la siguiente manera:

X = sin( time*velocityX )* radiusX + initialPositionInX;
Y = cos( time*velocityY )* radiusY + initialPositionInY;

Creamos una clase llamada particle y usamos una application para correrla:
Particle Class
package
{
import mx.core.UIComponent;

public class Particle extends UIComponent
{

/*---------------------------------------------------------------------------*/
/*----------------------------- START VARIABLES -----------------------------*/
/*---------------------------------------------------------------------------*/ 

private var _particleColor:uint = 0x000000;
private var _particleSize:int = 2;

/*---------------------------------------------------------------------------*/
/*------------------------------ END VARIABLES ------------------------------*/
/*---------------------------------------------------------------------------*/ 

/*****************************************************************************/

/*---------------------------------------------------------------------------*/
/*--------------------------- START INIT FUNCTIONS --------------------------*/
/*---------------------------------------------------------------------------*/

public function Particle()
{
super();
}

/*---------------------------------------------------------------------------*/
/*---------------------------- END INIT FUNCTIONS ---------------------------*/
/*---------------------------------------------------------------------------*/

/**************************************************************************/

/*---------------------------------------------------------------------------*/
/*------------------------------ START GET SET ------------------------------*/
/*---------------------------------------------------------------------------*/

public function get particleColor():uint{
return _particleColor;
}
public function set particleColor(value:uint):void{
_particleColor = value;
invalidateDisplayList();
}

public function get particleSize():int{
return _particleSize;
}
public function set particleSize(value:int):void{
_particleSize = value;
invalidateDisplayList();
}

/*---------------------------------------------------------------------------*/
/*------------------------------- END GET SET -------------------------------*/
/*---------------------------------------------------------------------------*/

/**************************************************************************/

/*---------------------------------------------------------------------------*/
/*------------------------- START OVERRIDE FUNCTION -------------------------*/
/*---------------------------------------------------------------------------*/

override protected function updateDisplayList( unscaledWidth:Number, unscaledHeight:Number): void 
{
super.updateDisplayList(_particleSize,_particleSize);
graphics.clear();
graphics.lineStyle(1,_particleColor,1);
graphics.beginFill(_particleColor,1);
graphics.drawCircle(0,0,_particleSize);
graphics.endFill();
}

/*---------------------------------------------------------------------------*/
/*------------------------- END OVERRIDE FUNCTION ---------------------------*/
/*---------------------------------------------------------------------------*/

}
}

The Application
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" frameRate="120" 
creationComplete="creationCompleteHandler(event)" layout="absolute" 
width="415" height="300" backgroundColor="0xFFFFFF"  xmlns:local="*" 
backgroundGradientAlphas="[1.0, 1.0]" 
backgroundGradientColors="[#FFFFFF, #FFFFFF]" themeColor="#FFFFFF" 
borderColor="#000000" borderStyle="solid" >
<mx:Script>
<![CDATA[
import mx.events.NumericStepperEvent;
import mx.events.ColorPickerEvent;
import mx.controls.Image;
import mx.core.UIComponent;
import mx.events.FlexEvent;

/*---------------------------------------------------------------------------*/
/*----------------------------- START VARIABLES -----------------------------*/
/*---------------------------------------------------------------------------*/ 

private var time:Number =0;
private var xo:Number = 0;
private var yo:Number = 0;
private var velocityX:Number = 1;
private var velocityY:Number = 1;
private var radiusX:Number = 100;
private var radiusY:Number = 100;
private var myCont:Canvas;
private var myImage:Image;
private var myParticle:Particle;

/*---------------------------------------------------------------------------*/
/*------------------------------ END VARIABLES ------------------------------*/
/*---------------------------------------------------------------------------*/ 

/*****************************************************************************/

/*---------------------------------------------------------------------------*/
/*--------------------------- START INIT FUNCTIONS --------------------------*/
/*---------------------------------------------------------------------------*/

private function creationCompleteHandler(event:FlexEvent):void{
this.addEventListener(Event.ENTER_FRAME,enterFrameHandler);
}
private function initParticleHandler(event:FlexEvent):void{
myCont = new Canvas;
myCont.percentWidth = 100;
myCont.percentHeight = 100;
myCanvas.addChild(myCont);
myParticle = new Particle;
myParticle.particleSize = 2;
myParticle.particleColor = 0xFF0000;
xo = myParticle.x = myCanvas.width/2;
yo = myParticle.y = myCanvas.height/2;
myImage = new Image;
myImage.percentWidth = 100;
myImage.percentHeight = 100;
myImage.alpha = 0.98;
myCont.addChild(myImage);
myCont.addChild(myParticle);
}

/*---------------------------------------------------------------------------*/
/*---------------------------- END INIT FUNCTIONS ---------------------------*/
/*---------------------------------------------------------------------------*/

/*****************************************************************************/

/*---------------------------------------------------------------------------*/
/*-------------------------- START EVENT FUNCTIONS --------------------------*/
/*---------------------------------------------------------------------------*/ 

/*-- START EVENT CAIRNGORM --*/

/*--- END EVENT CAIRNGORM ---*/

/***************************/

/*---- START EVENT FLEX -----*/
private function enterFrameHandler(event:Event):void{
time+=1/stage.frameRate;
myParticle.x = Math.sin(time*velocityX)*radiusX + xo; 
myParticle.y = Math.cos(time*velocityY)*radiusY + yo; 
myImage.source = new Bitmap(this.getUIComponentBitmapData(UIComponent(myCont)));
}
public function changeColorHandler(event:ColorPickerEvent):void{
myParticle.particleColor = event.color;
}
public function changeVelocityX(event:NumericStepperEvent):void{
velocityX = event.value;
}
public function changeVelocityY(event:NumericStepperEvent):void{
velocityY = event.value;
}
public function changeRadiusX(event:NumericStepperEvent):void{
radiusX = event.value;
}
public function changeRadiusY(event:NumericStepperEvent):void{
radiusY = event.value;
}
public function changeAlpha(event:NumericStepperEvent):void{
myImage.alpha = event.value;
}
public function changeRadius(event:NumericStepperEvent):void{
myParticle.particleSize = event.value;
}
public function clearImageHandler(event:MouseEvent):void{
this.removeEventListener(Event.ENTER_FRAME,enterFrameHandler);
myImage.source = new Bitmap();       
this.addEventListener(Event.ENTER_FRAME,enterFrameHandler);
}

/*----- END EVENT ------*/

/*---------------------------------------------------------------------------*/
/*-------------------------- END EVENT FUNCTIONS ----------------------------*/
/*---------------------------------------------------------------------------*/

/*****************************************************************************/

/*---------------------------------------------------------------------------*/
/*-------------------------- START OTHER FUNCTIONS --------------------------*/
/*---------------------------------------------------------------------------*/ 

public function getUIComponentBitmapData( target : UIComponent ) : BitmapData
{ 
var bd : BitmapData = new BitmapData( target.width, target.height );
var m : Matrix = new Matrix();
bd.draw( target, m );
return bd;  
}

/*---------------------------------------------------------------------------*/
/*-------------------------- END OTHER FUNCTIONS ----------------------------*/
/*---------------------------------------------------------------------------*/

]]>
</mx:Script>
<mx:HBox width="100%" height="100%">
<mx:Canvas width="78%" height="100%">
<mx:Form>
<mx:FormItem label="Color">
<mx:ColorPicker  change="changeColorHandler(event)"  
selectedColor="#FF0000"/>
</mx:FormItem>
<mx:FormItem label="Velocity X">
<mx:NumericStepper value="1" maximum="10" minimum="0" 
change="changeVelocityX(event)"/>
</mx:FormItem>
<mx:FormItem label="Velocity Y">
<mx:NumericStepper value="1" maximum="10" minimum="0" 
change="changeVelocityY(event)"/>
</mx:FormItem>
<mx:FormItem label="Radius X">
<mx:NumericStepper value="100" maximum="100" minimum="1" 
change="changeRadiusX(event)"/>
</mx:FormItem>
<mx:FormItem label="Radius Y">
<mx:NumericStepper value="100" maximum="100" minimum="1" 
change="changeRadiusY(event)"/>
</mx:FormItem>
<mx:FormItem label="Alpha">
<mx:NumericStepper value="0.98" maximum="1" minimum="0" 
stepSize="0.01"  change="changeAlpha(event)" />
</mx:FormItem>
<mx:FormItem label="Radius">
<mx:NumericStepper value="2" maximum="5" minimum="1" 
change="changeRadius(event)" />
</mx:FormItem>
<mx:FormItem label="Clear">
<mx:Button label="Clear" click="clearImageHandler(event)" />
</mx:FormItem>
</mx:Form>  
</mx:Canvas>
<mx:VBox width="100%" height="100%" >   
<mx:Canvas id="myCanvas" width="100%" height="100%" 
creationComplete="initParticleHandler(event)"/>
<mx:Label text="www.developyourdream.net" />
</mx:VBox>

</mx:HBox>
</mx:Application>
In this case I used the circle formula of Sin and Cos and put some variable inside the formula, this is the basic formulas in X and Y that we are using:

X = sin( angle )* radius + initialPositionInX;
Y = cos( angle )* radius + initialPositionInY;

So we can do it with animation we need to change the angle, we what to go faster so we can put a velocity to the angle.
The formula that we are using with the variable expresses like this:

X = sin( time*velocityX )* radiusX + initialPositionInX;
Y = cos( time*velocityY )* radiusY + initialPositionInY;

We created a class called particle and used in the applications:
Particle Class
package
{
import mx.core.UIComponent;

public class Particle extends UIComponent
{

/*---------------------------------------------------------------------------*/
/*----------------------------- START VARIABLES -----------------------------*/
/*---------------------------------------------------------------------------*/ 

private var _particleColor:uint = 0x000000;
private var _particleSize:int = 2;

/*---------------------------------------------------------------------------*/
/*------------------------------ END VARIABLES ------------------------------*/
/*---------------------------------------------------------------------------*/ 

/*****************************************************************************/

/*---------------------------------------------------------------------------*/
/*--------------------------- START INIT FUNCTIONS --------------------------*/
/*---------------------------------------------------------------------------*/

public function Particle()
{
super();
}

/*---------------------------------------------------------------------------*/
/*---------------------------- END INIT FUNCTIONS ---------------------------*/
/*---------------------------------------------------------------------------*/

/*****************************************************************************/

/*---------------------------------------------------------------------------*/
/*------------------------------ START GET SET ------------------------------*/
/*---------------------------------------------------------------------------*/

public function get particleColor():uint{
return _particleColor;
}
public function set particleColor(value:uint):void{
_particleColor = value;
invalidateDisplayList();
}

public function get particleSize():int{
return _particleSize;
}
public function set particleSize(value:int):void{
_particleSize = value;
invalidateDisplayList();
}

/*---------------------------------------------------------------------------*/
/*------------------------------- END GET SET -------------------------------*/
/*---------------------------------------------------------------------------*/

/*****************************************************************************/

/*---------------------------------------------------------------------------*/
/*------------------------- START OVERRIDE FUNCTION -------------------------*/
/*---------------------------------------------------------------------------*/

override protected function updateDisplayList( unscaledWidth:Number, unscaledHeight:Number): void 
{
super.updateDisplayList(_particleSize,_particleSize);
graphics.clear();
graphics.lineStyle(1,_particleColor,1);
graphics.beginFill(_particleColor,1);
graphics.drawCircle(0,0,_particleSize);
graphics.endFill();
}

/*---------------------------------------------------------------------------*/
/*------------------------- END OVERRIDE FUNCTION ---------------------------*/
/*---------------------------------------------------------------------------*/

}
}

The Application
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" frameRate="120" 
creationComplete="creationCompleteHandler(event)" layout="absolute" 
width="415" height="300" backgroundColor="0xFFFFFF"  xmlns:local="*" 
backgroundGradientAlphas="[1.0, 1.0]" 
backgroundGradientColors="[#FFFFFF, #FFFFFF]" themeColor="#FFFFFF" 
borderColor="#000000" borderStyle="solid" >
<mx:Script>
<![CDATA[
import mx.events.NumericStepperEvent;
import mx.events.ColorPickerEvent;
import mx.controls.Image;
import mx.core.UIComponent;
import mx.events.FlexEvent;

/*---------------------------------------------------------------------------*/
/*----------------------------- START VARIABLES -----------------------------*/
/*---------------------------------------------------------------------------*/ 

private var time:Number =0;
private var xo:Number = 0;
private var yo:Number = 0;
private var velocityX:Number = 1;
private var velocityY:Number = 1;
private var radiusX:Number = 100;
private var radiusY:Number = 100;
private var myCont:Canvas;
private var myImage:Image;
private var myParticle:Particle;

/*---------------------------------------------------------------------------*/
/*------------------------------ END VARIABLES ------------------------------*/
/*---------------------------------------------------------------------------*/

/*****************************************************************************/

/*---------------------------------------------------------------------------*/
/*--------------------------- START INIT FUNCTIONS --------------------------*/
/*---------------------------------------------------------------------------*/

private function creationCompleteHandler(event:FlexEvent):void{
this.addEventListener(Event.ENTER_FRAME,enterFrameHandler);
}
private function initParticleHandler(event:FlexEvent):void{
myCont = new Canvas;
myCont.percentWidth = 100;
myCont.percentHeight = 100;
myCanvas.addChild(myCont);
myParticle = new Particle;
myParticle.particleSize = 2;
myParticle.particleColor = 0xFF0000;
xo = myParticle.x = myCanvas.width/2;
yo = myParticle.y = myCanvas.height/2;
myImage = new Image;
myImage.percentWidth = 100;
myImage.percentHeight = 100;
myImage.alpha = 0.98;
myCont.addChild(myImage);
myCont.addChild(myParticle);
}

/*---------------------------------------------------------------------------*/
/*---------------------------- END INIT FUNCTIONS ---------------------------*/
/*---------------------------------------------------------------------------*/

/*****************************************************************************/

/*---------------------------------------------------------------------------*/
/*-------------------------- START EVENT FUNCTIONS --------------------------*/
/*---------------------------------------------------------------------------*/ 

/*-- START EVENT CAIRNGORM --*/

/*--- END EVENT CAIRNGORM ---*/

/***************************/

/*---- START EVENT FLEX -----*/
private function enterFrameHandler(event:Event):void{
time+=1/stage.frameRate;
myParticle.x = Math.sin(time*velocityX)*radiusX + xo; 
myParticle.y = Math.cos(time*velocityY)*radiusY + yo; 
myImage.source = new Bitmap(this.getUIComponentBitmapData(UIComponent(myCont)));
}
public function changeColorHandler(event:ColorPickerEvent):void{
myParticle.particleColor = event.color;
}
public function changeVelocityX(event:NumericStepperEvent):void{
velocityX = event.value;
}
public function changeVelocityY(event:NumericStepperEvent):void{
velocityY = event.value;
}
public function changeRadiusX(event:NumericStepperEvent):void{
radiusX = event.value;
}
public function changeRadiusY(event:NumericStepperEvent):void{
radiusY = event.value;
}
public function changeAlpha(event:NumericStepperEvent):void{
myImage.alpha = event.value;
}
public function changeRadius(event:NumericStepperEvent):void{
myParticle.particleSize = event.value;
}
public function clearImageHandler(event:MouseEvent):void{
this.removeEventListener(Event.ENTER_FRAME,enterFrameHandler);
myImage.source = new Bitmap();       
this.addEventListener(Event.ENTER_FRAME,enterFrameHandler);
}

/*----- END EVENT FLEX ------*/

/*---------------------------------------------------------------------------*/
/*-------------------------- END EVENT FUNCTIONS ----------------------------*/
/*---------------------------------------------------------------------------*/

/*****************************************************************************/

/*---------------------------------------------------------------------------*/
/*-------------------------- START OTHER FUNCTIONS --------------------------*/
/*---------------------------------------------------------------------------*/ 

public function getUIComponentBitmapData( target : UIComponent ) : BitmapData
{ 
var bd : BitmapData = new BitmapData( target.width, target.height );
var m : Matrix = new Matrix();
bd.draw( target, m );
return bd;  
}

/*---------------------------------------------------------------------------*/
/*-------------------------- END OTHER FUNCTIONS ----------------------------*/
/*---------------------------------------------------------------------------*/

]]>
</mx:Script>
<mx:HBox width="100%" height="100%">
<mx:Canvas width="78%" height="100%">
<mx:Form>
<mx:FormItem label="Color">
<mx:ColorPicker  change="changeColorHandler(event)"  
selectedColor="#FF0000"/>
</mx:FormItem>
<mx:FormItem label="Velocity X">
<mx:NumericStepper value="1" maximum="10" minimum="0" 
change="changeVelocityX(event)"/>
</mx:FormItem>
<mx:FormItem label="Velocity Y">
<mx:NumericStepper value="1" maximum="10" minimum="0" 
change="changeVelocityY(event)"/>
</mx:FormItem>
<mx:FormItem label="Radius X">
<mx:NumericStepper value="100" maximum="100" minimum="1" 
change="changeRadiusX(event)"/>
</mx:FormItem>
<mx:FormItem label="Radius Y">
<mx:NumericStepper value="100" maximum="100" minimum="1" 
change="changeRadiusY(event)"/>
</mx:FormItem>
<mx:FormItem label="Alpha">
<mx:NumericStepper value="0.98" maximum="1" minimum="0" 
stepSize="0.01"  change="changeAlpha(event)" />
</mx:FormItem>
<mx:FormItem label="Radius">
<mx:NumericStepper value="2" maximum="5" minimum="1" 
change="changeRadius(event)" />
</mx:FormItem>
<mx:FormItem label="Clear">
<mx:Button label="Clear" click="clearImageHandler(event)" />
</mx:FormItem>
</mx:Form>  
</mx:Canvas>
<mx:VBox width="100%" height="100%" >   
<mx:Canvas id="myCanvas" width="100%" height="100%" 
creationComplete="initParticleHandler(event)"/>
<mx:Label text="www.developyourdream.net" />
</mx:VBox>

</mx:HBox>
</mx:Application>



Descargar Archivo y Ver Codigo Fuente:


Download File's and Source:

domingo, 22 de marzo de 2009

Mouse Events - Eventos del Mouse - Flex 3

Ejemplo a Elaborar en MXML y en ActionScrip:


Muchas veces queremos hacer cosas cuando ocurren ciertos eventos, como hacer clic sobre algo o pasar por arriba de un objeto, etc. Flex Tiene escrita varias clases para el manejo de eventos, estas clases son escritas completamente en action scrip las cuales algunos objetos heredan para facilitarnos las vida al momento de querer hacer algo cuando ocurra un evento en particular.
Hay que tener en cuanta solo 3 cosas cuando hablamos de eventos, saber que es un Dispacher, saber que es un Listener y saber que es un Event Object:

  • 1. Dispacher: El objeto que es manipulado por el usuario y que dispara el evento. No olvidemos de que además de que los eventos son disparados automáticamente como respuesta a una acción del usuario también podemos dispararlos manualmente con ActionScript. (sacado de: http://www.holaflex.com/?p=40).
  • 2. Event object : Este es un objeto creado de acuerdo al tipo de acción generada y es el elemento que toma información del dispatcher para compartirla con otros componentes. (sacado de: http://www.holaflex.com/?p=40).
  • 3. Listeners: Objetos que escuchan y responden a dichos eventos, es decir, son los objetos que están registrados para tomar una acción cuando cierto evento es disparado en algún otro objeto. (sacado de: http://www.holaflex.com/?p=40).
Una vez que sepamos esto bien podemos hacer un ejemplo en el cual tomamos una imagen y escuchamos todos 6 eventos seleccionados:
  • Evento mouseOut: Mouse Out dispara un evento cuando el mouse ya no está sobre la imagen, ósea si estamos parado sobre ella y nos salimos de ella por cualquiera de sus lados este evento se disparara, valido acotar que solo se dispara cuando sale, no es que se dispara varias veces muestras este fuera de la imagen.
  • Evento mouseOver: Mouse Over dispara un evento cuando el mouse entra a tocar la imagen, de igual manera se dispara solo cuando entra mas no varias veces por estar dentro de la imagen.
  • Evento mouseDown: Mouse Down dispara un evento cuando bajamos el botón izquierdo del mouse sobre la imagen, solo una vez mientras el botón este abajo esto no significa que se dispara varias veces mientras mantengamos apretado el botón.
  • Evento mouseUp: Mouse Up dispara un evento cuando soltemos el botón izquierdo sobre la imagen.
  • Evento click: Click dispara un evento cuando se hace clic k con el botón izquierdo del mouse, la diferencia entre click con mouse up y mouse down es que el clic tienen que ocurrir los 2 eventos tanto down como up sobre la imagen, en cambio si hacemos mouse down sobre la imagen y mantenemos presionado y nos salimos de la imagen y hacemos mouse up se contara el evento mouse down pero el mouse up no se disparara y de la misma forma si hacemos mouse down fuera de la imagen y dejamos presionado al pararnos sobre la imagen y soltar el botón se contara el mouse up pero el mouse down nunca se disparo.
  • Evento mouseMove: mouse move se dispara tantas veces como nos movamos dentro de la imagen, este evento entra varias veces y podemos ver esta acción en el ejemplo al colocar la posición del mouse dentro de la imagen, esta posición se refresca cada vez que hacemos un movimiento dentro de la imagen.
Los eventos también se pueden hacer en MXML o en AS 3.0 veamos el ejemplo escrito de las dos maneras:

Ejemplo I, escrito en MXML:







Codigo:





<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundColor="0xFFFFFF">
<mx:VBox  >
<mx:HBox >
<mx:Label text="Evento mouseOut:" />
<mx:Label id="idLabelAuxI" text="0" color="0xFF0000" />
</mx:HBox>
<mx:HBox >
<mx:Label text="Evento mouseOver:" />
<mx:Label id="idLabelAuxII" text="0" color="0xFF0000" />
</mx:HBox>
<mx:HBox >
<mx:Label text="Evento mouseDown:" />
<mx:Label id="idLabelAuxIII" text="0" color="0xFF0000" />
</mx:HBox>
<mx:HBox >
<mx:Label text="Evento mouseUp:" />
<mx:Label id="idLabelAuxIV" text="0" color="0xFF0000" />
</mx:HBox>
<mx:HBox >
<mx:Label text="Evento click:" />
<mx:Label id="idLabelAuxV" text="0" color="0xFF0000" />
</mx:HBox>
<mx:HBox >
<mx:Label text="Evento mouseMove:" />
<mx:Label id="idLabelAuxVI" text="0" color="0xFF0000" />
</mx:HBox>
<mx:Image id="idImagen" source="img/Dibujo.jpg"
mouseOut="idLabelAuxI.text = (int(idLabelAuxI.text)+1).toString()"
mouseOver="idLabelAuxII.text = (int(idLabelAuxII.text)+1).toString()"
mouseDown="idLabelAuxIII.text = (int(idLabelAuxIII.text)+1).toString()"
mouseUp="idLabelAuxIV.text = (int(idLabelAuxIV.text)+1).toString()"
click="idLabelAuxV.text = (int(idLabelAuxV.text)+1).toString()"
mouseMove="idLabelAuxVI.text = 'Mouse X: '+idImagen.mouseX +' Mouse Y: '+ idImagen.mouseY"
/>
</mx:VBox>
</mx:Application>






Ejemplo II, en MXML con AS 3.0:










Codigo:




<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundColor="0xFFFFFF"
creationComplete="init()">
<mx:Script>
<![CDATA[
private function init():void{
idImagen.addEventListener(MouseEvent.MOUSE_OUT,mouseOutHandler);
idImagen.addEventListener(MouseEvent.MOUSE_OVER,mouseOverHandler);
idImagen.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
idImagen.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler);
idImagen.addEventListener(MouseEvent.CLICK,mouseClickHandler);
idImagen.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler);
}
private function mouseOutHandler(e:MouseEvent):void{
idLabelAuxI.text = (int(idLabelAuxI.text)+1).toString();
}
private function mouseOverHandler(e:MouseEvent):void{
idLabelAuxII.text = (int(idLabelAuxII.text)+1).toString();
}
private function mouseDownHandler(e:MouseEvent):void{
idLabelAuxIII.text = (int(idLabelAuxIII.text)+1).toString();
}
private function mouseUpHandler(e:MouseEvent):void{
idLabelAuxIV.text = (int(idLabelAuxIV.text)+1).toString();
}
private function mouseClickHandler(e:MouseEvent):void{
idLabelAuxV.text = (int(idLabelAuxV.text)+1).toString();
}
private function mouseMoveHandler(e:MouseEvent):void{
idLabelAuxVI.text = 'Mouse X: '+idImagen.mouseX +' Mouse Y: '+ idImagen.mouseY;
}

]]>
</mx:Script>

<mx:VBox  >
<mx:HBox >
<mx:Label text="Evento mouseOut:" />
<mx:Label id="idLabelAuxI" text="0" color="0xFF0000" />
</mx:HBox>
<mx:HBox >
<mx:Label text="Evento mouseOver:" />
<mx:Label id="idLabelAuxII" text="0" color="0xFF0000" />
</mx:HBox>
<mx:HBox >
<mx:Label text="Evento mouseDown:" />
<mx:Label id="idLabelAuxIII" text="0" color="0xFF0000" />
</mx:HBox>
<mx:HBox >
<mx:Label text="Evento mouseUp:" />
<mx:Label id="idLabelAuxIV" text="0" color="0xFF0000" />
</mx:HBox>
<mx:HBox >
<mx:Label text="Evento click:" />
<mx:Label id="idLabelAuxV" text="0" color="0xFF0000" />
</mx:HBox>
<mx:HBox >
<mx:Label text="Evento mouseMove:" />
<mx:Label id="idLabelAuxVI" text="0" color="0xFF0000" />
</mx:HBox>
<mx:Image id="idImagen" source="img/Dibujo.jpg" />
</mx:VBox>
</mx:Application>






Los eventos no solo se aplican a las imágenes cada objeto o componente se le puede decir que dispare los eventos correspondientes a ellos, en otro tutorial veremos más eventos y en tutoriales de flex avanzado veremos cómo podemos crear nuestros propios eventos.
Saludos.

Descargar Archivos:

Hola Mundo 2 - Flex 3

Ejemplo a Elaborar en MXML y en ActionScrip:

MXML:


AS:


En este tutorial haremos un hola mundo dinámico, que cuanto se haga clic en el botón se cambie el texto de un label y colocaremos HOLA MUNDO. El ejemplo lo vamos a hacer de dos maneras la primera en MXML y la segunda en MXML con AS 3.0 para ver las dos caras de la moneda.


Ejemplo I, escrito en MXML:



Codigo:



<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:VBox width="100%" height="100%">
<mx:Label id="idLabel" text="Texto de Inicio"/>
<mx:Button label="Tutorial" click="{idLabel.text = 'Hola Mundo'}"/> 
</mx:VBox>
</mx:Application>





Ejemplo II, en MXML con AS 3.0:







Codigo:



<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

<mx:Script>
<![CDATA[
private var contador:int = 0

private function clickHandler(e:MouseEvent):void{
idLabel.text = "Hola Mundo "+contador;
contador++;
}
]]>
</mx:Script>

<mx:VBox width="100%" height="100%">
<mx:Label id="idLabel" text="Texto de Inicio"/>
<mx:Button label="Tutorial" click="{clickHandler(event)}"/> 
</mx:VBox>

</mx:Application>



Con este tutorial ahora somos capaces de crear títulos que se generen dinámicamente cada ve que le demos a un botón que nosotros queramos, personalizando el texto en las ocasión que necesitemos.
Saludos.

Descargar Archivos:

Hola Mundo Flex 3

Ejemplo a Elaborar en MXML y en ActionScrip:

Flex, tiene la capacidad de poder interpretar dos tipos de códigos de programación, se pueden usar códigos netamente en ActionScript 3.0 o se puede trabajar en MXML para los amantes del tag.
Tanto en un lenguaje como en el otro se puede lograr los mismos resultados y si nos atascamos en algún lado siempre existe la posibilidad de combinar los 2 lenguajes de programación en un mismo archivo.


Veamos un ejemplo de cómo colocaríamos un Label y como texto del mismo colocaremos HOLA MUNDO tanto en MXML como usando AS 3.0 y MXML a la vez.

Video




El ejemplo es bastante básico pero para empezar a conocer los lenguajes están bastante bien:

Ejemplo I, solo MXML:





Codigo:



<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Label text="Hola Mundo" />
</mx:Application>




Ejemplo II, solo MXML con AS 3.0:





Codigo:



<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
creationComplete="init()">
<mx:Script>
<![CDATA[
private function init():void{
idLabel.text = "Hola Mundo 2";
}
]]>
</mx:Script>

<mx:Label id="idLabel" />
</mx:Application>





Listo ahora podremos colocar labels personalizados con textos a nuestra preferencia en el próximo tutorial colocaremos el texto en una función y cuando le demos clic a un botón el label se llenara.
Saludos.


Descargar Archivos: