Juan develops in AS 3.0

October 21, 2009

Making sure papervision acknowledges Flex of its dimensions

Filed under: Flex, Papervision — juandevelops @ 4:02 pm

This is an effective way to load papervison into Flex.

In application include a UIComponent instance

<box:PaperVisionBoxid=”ppv/>

This is the UIComponent instance. Here we are getting feedback from mc to know the dimensions of its papervision content and in order to resize this UIComponent. In this way the application gets noticed of the new dimensions and pushes down or left depending of its layout.

//PaperVisionBox

<<?xml version=”1.0″ encoding=”utf-8″?>

<mx:UIComponentxmlns:mx=”http://www.adobe.com/2006/mxml” xmlns:box=”com.juandevelops.ppv.box.*

preinitialize=”this.onFlexEvent( event );”

addedToStage=”this.onFlexEvent(event);”

resize=”this.onFlexEvent(event);”>

<mx:Script>

<![CDATA[

import com.juandevelops.flesh.stage.StageEvent;

import com.juandevelops.flesh.stage.StageListener;

import com.juandevelops.ppv.cube.MotherCube;

import mx.events.FlexEvent;

private var mc:MotherCube

private function onFlexEvent( event:Event ):void

{

if( event.type == FlexEvent.PREINITIALIZE )

{

mc =new MotherCube();

this.addChild( mc );

}

else

if( event.type == Event.ADDED_TO_STAGE || event.type == Event.RESIZE )

{

this.invalidateSize();

}

}

override protected function measure():void

{

super.measure();

if( mc )

{

this.measuredWidth = mc.width;

this.measuredHeight = mc.height;

}

}

]]>

</mx:Script>

</mx:UIComponent>

Now it’s time to see the work done in MotherCube which is an instance os Sprite and is loading papervision, and in papervision we include a cube.

We can ignore most of the code and just pay attention to getters width and height.

Also important, not to include any other content but just papervision.

//MotherCube

package icom.juandevelops.ppv.cube

{

import flash.display.Sprite;

import flash.events.Event;

import flash.events.MouseEvent;

import flash.geom.Rectangle;

import org.papervision3d.cameras.CameraType;

import org.papervision3d.materials.ColorMaterial;

import org.papervision3d.materials.MovieMaterial;

import org.papervision3d.materials.utils.MaterialsList;

import org.papervision3d.objects.primitives.Cube;

import org.papervision3d.render.BasicRenderEngine;

import org.papervision3d.view.BasicView;

publicclass MotherCube extends Sprite

{

privatevar view:BasicView;

privatevar _cube:Cube;

privatevar list:MaterialsList;

privatevar cm:ClipMaterial;

privatevar mm:MovieMaterial;

publicfunction MotherCube()

{

view = new BasicView(600, 600, false, false, CameraType.FREE);

view.renderer = new BasicRenderEngine(); addChild(view);

view.viewport.interactive = true;

view.camera.z = -540;

list = new MaterialsList();

list.addMaterial( new ColorMaterial( 0xFFFFFF, “back” );

list.addMaterial( new ColorMaterial( 0×0099FF, 1, false ), “front” );

list.addMaterial( new ColorMaterial( 0xFF0000, 1, false ), “left” );

list.addMaterial( new ColorMaterial( 0xFFCC00, 1, false ), “right” );

list.addMaterial( new ColorMaterial( 0×93A070, 1, false ), “top” );

list.addMaterial( new ColorMaterial( 0×999999, 1, false ), “bottom” );

_cube = new Cube( list, 400, 400, 400 );

view.scene.addChild( _cube );

this.addEventListener( Event.ENTER_FRAME, onRenderViewport);

}

privatefunction onRenderViewport(e:Event): void

{

view.singleRender();

}

overridepublicfunctiongetwidth():Number

{

if( view )

return view.viewport.viewportWidth;

return 0;

}

overridepublicfunctionget height():Number

{

if( view )

return view.viewport.viewportWidth;

return 0;

}

publicfunctionget cube():Cube

{

returnthis._cube;

}

}

}

In my appliation I included the box below having the scrollers, and they are pushed down as the content in PaperVisionBox found out the dimensions of MotherCube

I Hope this helps, please let me know.. I am try to share my work knowledge and I never get any comments.

October 12, 2009

Shortcut to include NativeMenu in desktop

Filed under: Flex — juandevelops @ 3:36 pm

I like the idea of writing code that will save me from thinking more than i want.. in this case appending a NativeMenu required to set a condition when adding one to a windows or mac computer. So i wrote a class and also noticed there was an issue with Mac not able to display the NativeMenu; fortunately, ThanksMister found a solution.. :) and what i did here is follow his suggestion..

Here is how simple i write my code and include the NativeMenu using my class NativeMenuUtil, which requires first for you to set stage to it, and then it takes care of the rest..

NativeMenuUtil.stage = this.stage;

var nativeMenu:NativeMenu = new NativeMenu();

var item:NativeMenuItem;

item = new NativeMenuItem( “Menu 1″ );

nativeMenu.addItem( item );

item = new NativeMenuItem( “Menu 2″ );

nativeMenu.addItem( item );

NativeMenuUtil.applicationMenu = nativeMenu;

//here is the code…

package com.juandevelops.air.menu

{

import flash.desktop.NativeApplication;

import flash.display.NativeMenu;

import flash.display.NativeMenuItem;

import flash.display.NativeWindow;

import flash.display.Stage;

public class NativeMenuUtil

{

private static var _stage:Stage;

public static function set stage( stage:Stage ): void

{

_stage = stage;

}

public static function get applicationMenu():NativeMenu

{

return getNativeMenu();

}

public static function set applicationMenu( nativeMenu:NativeMenu ): void

{

var myNativeMenu:NativeMenu = getNativeMenu();

if ( NativeWindow.supportsMenu )

{

myNativeMenu = nativeMenu;

}

else

{

//sample helped me so much, i was going nuts why i couldn’t display menu on a mac.

//http://thanksmister.com/index.php/archive/air-nativemenu-issue-on-mac/comment-page-1/#comment-16493

var menuItem:NativeMenuItem = new NativeMenuItem( “Application Menu” );

menuItem.submenu = nativeMenu;

myNativeMenu.addItem(menuItem);

}

}

private static function getNativeMenu():NativeMenu

{

if ( NativeWindow.supportsMenu )

return _stage.nativeWindow.menu as NativeMenu;

return NativeApplication.nativeApplication.menu as NativeMenu;

}

}

}

Here is what it looks like when I run the application

October 2, 2009

Getting the screen dimensions for Air Windows.

Filed under: air — juandevelops @ 1:38 am

I want just to make it easier to get the screen dimensions found under the screen. I used the code found here: http://cookbooks.adobe.com/index.cfm?event=showdetails&postId=10823

So i just created a class that is static, and gives me the rectangle dimensions just when i need it and saving me writing the code..

package com.juandevelops.air.utils
{
import flash.display.NativeWindow;
import flash.display.NativeWindowInitOptions;
import flash.display.NativeWindowSystemChrome;
import flash.display.StageDisplayState;
import flash.events.EventDispatcher;
import flash.geom.Rectangle;

public class ScreenUtils
{
public static function getScreenRectangle():Rectangle
{
//set the window options before creating the window…
var options:NativeWindowInitOptions = new NativeWindowInitOptions()
options.systemChrome=NativeWindowSystemChrome.NONE;
options.transparent=true;

var tmpWindow:NativeWindow = new NativeWindow( options );

//blow up the window to take up the full size of the monitor…
tmpWindow.stage.displayState = StageDisplayState.FULL_SCREEN;

var rect:Rectangle = tmpWindow.bounds.clone();

//get rid of invisible window
tmpWindow.close();

return rect;
}
}
}

so it will be easier to use ScreenUtils.getScreenRectangle() anywhere else.

August 29, 2009

Clipboard set and get data from a custom object.

Filed under: ActionScript 3.0, air — juandevelops @ 6:42 pm

In Air, using ClipBoard allows for different object types to be copy and paste from one air application into another, from a non-air application into an air application, or viceversa.

As i  looked into lynda.com air tutorials: http://www.lynda.com/home/DisplayCourse.aspx?lpk2=596
I learned that from an air application i can copy data items in the following formats text, bitmap, html text. Those formats work well if i paste the clipboard data to a non-air application such as copying bitmap data to fireworks.

Their tutorial explained the possibility to also disguise an instance of a custom class as a regular object, and use that datatype to paste it into another air application.

There are instances of classes in AIR which can be transparently copy and paste from one app to another such as the case of ArrayCollection.
The secret behind is their classes implement IExternalizable.

Here is my first atttempt making use of accessing the copied data in clipboard as a simple object

//- my class

package model
{
public class Lifter
{
public static const FORMAT:String = “model.Lifter”;
public var name:String;
public var age:uint;
public var weight:uint;

public function Lifter()
{
}

public function toString():String
{
return “Lifter[ " + this.name +", " + this.age + ", "+ this.weight + " ]“;
}
}
}

//app A

var l:Lifter = new Lifter(  );
l.name = “Juan”;
l.age = 34;
l.weight = 10;

var c:Clipboard = Clipboard.generalClipboard;
c.clear();
c.setData( Lifter.FORMAT, l  );

//app B

var c:Clipboard = Clipboard.generalClipboard;

if( c.hasFormat( Lifter.FORMAT ) )
{
var l:Object
l = c.getData( Lifter.FORMAT ) as Object;
trace( l.name  );
}
else
{
trace( “we are sorry format is not included.. ” );
}

The first attempted worked, but the data is no longer of type Lifter instead just a simple object.

Second attempt make the data in clipboard be copied an instance of type Lifter and be able to get the data back as of type Lifter.

I follow David Tucker’s advice of using registerClassAlias in both sides of the coin for the object to appear transparent as being of its class type. It is great to read his blog, and helped me to have this example

Well, i had to make the changes to my Lifter class, implementing IExternalizable, in the adobe livedocs, they describe members of the class not being public but in my example i have my members public, in the same way as in David’s example.

package model
{
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;

public class Lifter implements IExternalizable
{
public static const FORMAT:String = “model.Lifter”;
public var name:String;
public var age:uint;
public var weight:uint;

//in my first attempt i set the members above as private, and set parameters in the constructor to assign them to the class
//when i tried to get this instance from the clipboard, i had argument errors as i was missing those arguments.
//best advice, make your constructor have no parameters, and you can set your members as private, and use setters and getters
//to read and write to them.

public function Lifter(  )
{
}

public function toString():String
{
return “Lifter[ " + this.name +", " + this.age + ", "+ this.weight + " ]“;
}

public function writeExternal(output:IDataOutput):void
{

output.writeUTF( this.name );
output.writeUnsignedInt( this.age );
output.writeUnsignedInt( this.weight );
}

public function readExternal(input:IDataInput):void
{

this.name = input.readUTF();
this.age = input.readUnsignedInt();
this.weight = input.readUnsignedInt();
}
}
}

//now here is my app A

var l:Lifter = new Lifter(  );
l.name = “Juan”;
l.age = 34;
l.weight = 204;

registerClassAlias( “Lifter”, Lifter );

var c:Clipboard = Clipboard.generalClipboard;
c.clear();
c.setData( Lifter.FORMAT,  l );

//now here is my app B

var c:Clipboard = Clipboard.generalClipboard;
registerClassAlias( “Lifter”, Lifter );

if( c.hasFormat( Lifter.FORMAT ) )
{

var l:Lifter;
l = c.getData( Lifter.FORMAT, ClipboardTransferMode.CLONE_PREFERRED ) as Lifter;
trace( l ); //output: Lifter[ Juan, 34, 10 ]
}
else
{
trace( “we are sorry format is not included.. ” );
}

July 31, 2009

Flex lending its mx.styles.StyleManager to flash.text.StyleSheet

Filed under: ActionScript 3.0, Flash, Flex — juandevelops @ 3:27 pm

Before reading, please leave a comment if this blog was any helpful. Thanks.

I believe that a Flex application should not be taken too seriously just as Flex application but allow space for Flash work or just Actionscript. There are times it is easier to have a UIComponent and take case of working with the simple forms of Flash such as Textfield, Sprites, and Movieclips. I also realize that working with TextField.stylesheet seems like a lot of work, and specially when it is easy for you to create your own embedded css files for your Flex project. Wouldn’t it look clean to have a css file to allow class Stylesheet to benefit from it? I think is great to allow Flex and ActionScript/Flash content benefit at the same time.

So I did a research and found a way to get the StyleManager class in flex to provide different object for different css classes. Here is an example:

/style/Global.css

.Paragraph
{
color: #FF3600;
fontFamily: “Magneto”;
leading: -0.5;
size: 34;
}

.Hungria
{
fontFamily: “Verdana”;
color: #444B4C;
leading: -0.5;
fontSize: 19;
}

//my class allows me to lend css classes from stylemanager to my stylesheet

package com.juandevelops.flesh.text
{
import flash.text.StyleSheet;

import mx.styles.CSSStyleDeclaration;
import mx.styles.StyleManager;

public class StyleFactory
{

//3. returns an object for a css class declaration.
public static function getStyleObject( styleName:String ):Object
{
var cssStyle:CSSStyleDeclaration = StyleManager.getStyleDeclaration( styleName );

if( !cssStyle )
{
trace( “com.juandevelops.flesh.utils.StyleFactory has no style ” + styleName );
return {};

}

return new cssStyle.factory();
}

//2. allows one css class to be attached to the stylesheet.
public static function applyToStyleSheet( styleSheet:StyleSheet, styleName:String ):void
{
var styleObject:Object = getStyleObject( styleName );

//color requires to be in this format #CCCCCC
if( styleObject.color )
{
styleObject.color = “#” + styleObject.color.toString( 16 );
}

//color requires to be in this format #CCCCCC

if( styleObject.color )
styleObject.color = “#” + styleObject.color.toString( 16 );

styleSheet.setStyle( styleName, styleObject );

}

//1. creates a stylesheet and includes css classes from Stylemanager.
public static function createStyleSheet( styleList:Array ):StyleSheet
{
var styleSheet:StyleSheet = new StyleSheet();
var len:uint = styleList.length;
var i:uint;

for( i = 0; i < len; i++ )
{
applyToStyleSheet( styleSheet, String( styleList[i] ) );
}

return styleSheet;
}
}
}

CSSApplication.mxml

<![CDATA[
import com.juandevelops.flesh.text.StyleFactory;
import mx.events.StyleEvent;
import flash.text.TextField;
import flash.text.StyleSheet;
import mx.events.FlexEvent;

<mx:Style source="/style/Global.css" />

<mx:Script>

<[[cdata

private function onCreationComplete( event:FlexEvent ):void
{
//i want to create a stylesheet based on the given
//css class declarations in my Global.css file.

//0.
var styleSheet:StyleSheet = StyleFactory.createStyleSheet( [ ".Paragraph", ".Hungria" ] );

var txt:TextField = new TextField();
txt.width = 300;

txt.styleSheet = styleSheet;
txt.htmlText = “<p class=’Paragraph’>hola</p><p class=’Hungria’> Hungria</p>”;

this.ui.addChild( txt );

}

]]>

This can be grateful for an embedded swf or a custom Flash component for Flex.

I hope this helps you a lot. And if so drop me a line.

July 15, 2009

BrowserManager and issues in Firefox

Filed under: Uncategorized — juandevelops @ 3:28 pm

I was able to use the browsermanager with success when listening for browser evernts happening at BrowserChangeEvent.APPLICATION_URL_CHANGE but for BrowserChangeEvent.BROWSER_URL_CHANGE i was not able to read any events.

IE didn’t give me any problems..

but here is the solution.

I suggest you set this on a preinitialize event on your main application:

var browserManager:IBrowserManager = BrowserManager.getInstance();
browserManager.init(“”, “site”);

After i added these two lines, all my browser history in firefox was working perfectly.

June 16, 2009

wordpress.com simply doesn’t support flash

Filed under: Flash, Flex — juandevelops @ 3:45 pm

if you read their policies. they will clearly say. we do not allow flash because of security policies. i am not making this up and many blogs people keep trying to find a way to get away. Now if you have a hosting site and it supports php for instance, then you can download wordpress and upload it to your site and with some configurations to your database you can use it, and in that way you can also include a plugin to embed swf’s. so no no no no.. many times no.. unless you want to add a hyperlink.

I believe wordpress should go along like myspace. They allow you to embed swf’s but they won’t allow you to do any javascript calls. and alllow us all to use swf’s. it’s so important.

now if you really want to have a free blog and use flash use blogspot.
http://com-juancho.blogspot.com/

you can see my swf embedded worked, and i only had to use an object tag to do the embed. as i write i am still upset for the time i wasted trying to look for a solution in wordpress. there is no such thing as embedding swf’s. that’s very bad, and specially coming from a blog that is considered to be so popular.

May 20, 2009

having a flex’s swf be resized at runtime.

Filed under: Flex, javascript — juandevelops @ 3:52 pm

if you are working on an application that requires to update itsef and make all the content fit within, you will need to make use of swfobject. In this way the div that embeds the swf can be resized using javascript, and that way the application has more space for its content.

 

1. so first thing use swfobject 

2. make flex call a javascript function which will take charge in updating the div where the swf of the flex application is embeded.

3. set the flex application to listen to Stage’s resize event.

 

Here is a sample:

 

1.  use swf object:http://blog.deconcept.com/swfobject/

<div id=”galleryLayer” >

<a href=”http://www.adobe.com/go/EN_US-H-GET-FLASH”>Get the Flash Player</a> to see this gallery.

<script type=”text/javascript”>

 

   var flashvars = {};

                       //let flex know if based on the browser you are allowed to resize the swf or not, the code is below…

    flashvars.resizable = isResizable() ? “true” : “false”;

    flashvars.layer = “galleryLayer”;

 

var params = {};

params.menu = “false”;

params.quality = “best”;

params.scale = “noscale”;

params.salign = “tl”;

params.bgcolor = “#869ca7″;

params.allowscriptaccess = “always”;

params.allowfullscreen = “true”;

params.wmode = “transparent”;

 

var attributes = {};

attributes.name = “flexGallery”;

attributes.align = “middle”;

 

swfobject.embedSWF(“Gallery.swf”, “galleryLayer”, “400″, “400″, “9.0.15″, “/common/flash/expressInstanll.swf”, flashvars, params, attributes );

</script>

 2.  include the javascript code so flex can call to modify the swf:

 

//flex calls this function, passing the layer id, and dimensions

function setSize( w, h )

{

setTimeout( “resizeLayer(” + w + “,” + h + “)”, 100 );

}

 

 

//chrome doesn’t allowed me to inmediately change the swf dimensions

//so i used a timeout to modify the dimensions 

function resizeLayer( w, h )

{

        document.getElementById(“galleryLayer”).style.width = w + “px”;

        document.getElementById(“galleryLayer”).style.height = h +”px”;

}

 

//can the browser allow the swf to resize?

function isResizable()

{

var ua = navigator.userAgent.toLowerCase();

var opera = ua.indexOf(“opera”);

var safari = ua.indexOf( “safari” );

//alert(ua.substr((safari+7),5))

if( document.getElementById ){

 

if(opera == -1)

{

 

if( safari != -1 )

{

//if safari.version >= 3 return “true”, else return “false”

if(ua.substr((safari+7),5)>=522.1){

return “true”;}else{

return “false”;

}

 

}else{return “true”; }

}

 

else

if(parseInt(ua.substr(opera+6, 1)) >= 7)

{

return “true”;

}

}

return “false”;

}

 

//here is the flex call to javascript:

 

if( this.stage.loaderInfo.parameters[ "resizable" ] == “true” )

 ExternalInterface.call( “setSize”, newW, newH );

3. just because your swf graciously changed in size doesn’t mean the application dimensions are different, therefore this code is necessary in the application:

this.stage.addEventListener( Event.RESIZE, this.onStageResize );

 

private function onStageResize( event:StageEvent ):void

{

 this.width = this.stage.stageWidt

this.height = this.stage.stageHeight; 

 

}

 

do you have any questions? let me know if this post helped you as well..

May 14, 2009

calculating the internal dimensions of a Tile.

Filed under: Uncategorized — juandevelops @ 5:27 pm
Tags: , , ,

i am working on a project where a tile that holds a bunch of children requires the swf gets resized so the Tile expands to fit all its children and no need to scroll.

I spent hours trying to figure out if there was an explit detail of the internal dimensions, i came to this conclusion.

var actualWidth:Number = this.myTile.width;

if( this.myTile.maxHorizontalScrollPosition > 0 )
actualWidth =  this.myTile.width  + this.myTile.maxHorizontalScrollPosition – this.myTile.verticalScrollBar.width;

var actualHeight:Number = this.myTile.height;

if( this.myTile.maxVerticalScrollPosition > 0 )
actualHeight = this.myTile.height + this.myTile.maxVerticalScrollPosition – this.myTile.horizontalScrollBar.height;

this.myTile.width = actualWidth; this.myTile.height = actualHeight;

Just remember i am using a bunch of children and wanted to find a more explicit way to calculate the real width and height included inside the tile.

p.s. if you find an easier way,, i appreaciate if you let me know… :)

March 20, 2009

How To Load and Control an external SWF

Filed under: Flex — juandevelops @ 5:27 pm

Loading and Controlling SWF from Flex

 

To load a swf we use tag
<mx:SWFLoader id=”mySWF” source=”url.swf” />

Be advice if the swf is from another domain, you are require to use System.

Flash.system.Security.loadPolicyFile( “ http://domain.com/crossdomain.xml” );

 

When the swf is loaded if it comes from the same domain, then it can be treated as if the FLA was set to a specific class

which is also found in the flex project. Otherwise, if the swf is from a separate domain, treat it as MovieClip.

 

In my case I set my fla to be of type Box and both files are also part of my Flex Project. :) Now My flex application can treat the swf

based on a class it recognizes.

Now go ahead and load the swf and set it’s type.

 

 

Now I can start interacting with my swf as usual, and also access a method from my Box class called boxColor();

I click button btnColor, this alert pop up showed up.

 

 

 

 

Next Page »

Blog at WordPress.com.