Category Articles

Buttons the indieas way 1

Aug16

As announced I optimized the usage of Buttons in the indieas library.

SimpleButton with disabled state

So the first I create a MovieClip with the different states:

As you can see there is an additional disabled state compared to the normal SimpleButton. So one way to use this MovieClip now as a Button in my Actionscript project is to export it as a Class:

Now when I use the exported swc file as a library in my Actionscript project I can easily create a Button like that:

var but:Button = Button.FromClass( DemoButton );
but.enable = false; // to jump to the disabled state.
addChild( but );

Another way to create a Button is to turn an already placed DemoButton MovieClip into a Button. So you don’t have to add it as a Child and it just turns it into a Button instance:

var but:Button = Button.FromMC( myDemoButton ); // where myDemoButton is an instance of the DemoButton

Adding scripting animations

This is the simplest usage but more often I like to add scripting animations on mouse events. So for example you have an icon on the button that should pop-up on roll-over. The Button class provides an easy way to access MovieClips placed on the timeline. So lets enhance the DemoButton with an icon:

As this Button is special we create an IconButton class:

package {

	import org.indieas.tween.easing.Bounce;
	import org.indieas.tween.easing.Elastic;
	import org.indieas.tween.property.Scaler;
	import org.indieas.widget.button.Button;

	public class IconButton extends Button {

		public function IconButton() {
			super();
		}

		protected override function onOver():void {
			Scaler.To( stateManager.icon, 0.7, 1.5, 1.5, Elastic.easeOut ).start();
		}

		protected override function onUp():void {
			Scaler.To( stateManager.icon, 0.3, 1, 1, Bounce.easeOut ).start();
		}
	}
}

The animation is now done by the indieas tween engine, but you can use any tweening engine you like. The stateManager handles the access to the icon MovieClip that we placed earlier.

To instantiate the IconButton we can again do it with a MovieClip or the class:

var but:IconButton = new IconButton();

but.buildFromClass( DemoButton );
addChild( but );

// or
but.buildFromMC( myDemoButton );

This results in a button like this:

Get Adobe Flash player

One big advantage of this approach is that you can have different MovieClips with other assets that uses the same Button class. For example to create another IconButton that just looks different you can call the buildFrom* method with another MovieClip/Class.

Buttons with labels

There is another handy class called LabelButton, where you place a TextField into the Button called label. You have now methods where you can style the Text with CSS. For example:

var label:LabelButton = LabelButton.FromMC( draft.labelButton );
label.setStyle( upFormat ); // set the style for all states.
label.setStyle( overFormat, Button.OVER_STATE ); // specific style for over state.
label.embedFont = true;
label.antiAliasType = AntiAliasType.ADVANCED;
label.gridFitType = GridFitType.SUBPIXEL;

So thats it, if you like to use these classes too,  go to the libary page and download the latest classes.

to be open source or not – thats the question 2

Dec28

In the last weeks I was thinking about open sourcing my modular framework. So far I kept it closed source and got some money if somebody used it in commercial projects. But I’m not very happy with this solution as it costs quite an effort to use a commercial framework.

That why I though it would be better to distribute it for free and open source.  My major problem is that I spent many hours in developing modular and earning some money to redeem would be great. So to help me making a decision I made my own list of advantages for going open source;

Advantages:

  • everybody can use it for free.
  • can use open source platforms for advertising.
  • other programmers may join the development.
  • higher possibility for viral marketing without to much effort.
  • same level with other open source frameworks. No “why should I paid for this” questions.
  • ?maybe? get some money by donations
  • possibility to sell commercial modules to companies.

I’m wondering if there is somebody with experience with donations? Does this really work? Or maybe other inputs for changing to open source? Just let me know…

Onscreen Keyboard with AIR 4

Nov14

In one of my last projects I had to develop an air application with an onscreen keyboard that is working with flash as with the internal html browser of air.

I realized pretty quickly that this isn’t that easy as it seams. There are multiple problems especially with the html view:

  • how do i get the focus in the html view to add letters.
  • how do i get the selection to add chars on the right position.
  • how do i know when a user clicks and inputfield/textarea.
  • how do i prevent that flash do set the focus on the keyboard when I click on a letter sprite.

After some experiments I discovered the really nice javascript support of the internal browser. So my first problem was already gone, when I found the javascript command:

var webView:HTMLLoader = new HTMLLoader();
//...later, to get the element with the focus call:
var element:Object = webView.window.document.activeElement;

I wasn’t really into javascript so I was surprised to discover even more possibilities. Now with the focus I can place an onscreen keyboard made with flash and get the activeElement of the htmlloader and add characters to it. something like this:

var inputField:Object = webView.window.document.activeElement;
if( inputField != null ) {
   var select:Number = addScreenBoardText( e.char, inputField, "value", "selectionStart", "selectionEnd" );
   inputField.setSelectionRange( select, select );
}

The function where I add the char and return the selection where the cursor should be set:

private function addScreenBoardText( insert:String, object:Object, textAttribute:String, selectionStartAttribute:String, selectionEndAttribute:String ):Number {
  var selectionStart:Number = object[ selectionStartAttribute ];
  var selectionEnd:Number = object[ selectionEndAttribute ];
  var original:String = object[ textAttribute ];
  var newText:String = original.substring( 0, selectionStart ) + insert + original.substr( selectionEnd );
  object[ textAttribute ] = newText;
  return selectionStart + insert.length;
}

Why I make this weird looking function is because I can use it also for the flash TextField just with different parameters. So now we can add letters to a textfield in a html view as a flash TextField. But one big problem is that we loose the focus every time we click on our on screen keyboard. And there is a way to prevent the change of the focus which is very handy in this situation:

 // in our main application class we listen to the mouse focus change event.
addEventListener( FocusEvent.MOUSE_FOCUS_CHANGE, onMouseFocus );

// in the listener we check if the relatedObject is a Key,Screenboard ( these are my classes for the Keyboard that get mouseclicks )
// then we prevent the default behaviour of the event. which means no focus change is triggered.
private function onMouseFocus( fe:FocusEvent ):void {
if( fe.relatedObject is Key || fe.relatedObject is ScreenBoard ) fe.preventDefault();
}

We saw earlier that is was possible to write to javascript objects as normal in actionscript. I was even more surprised as its possible to listen to javascript events with actionscript functions. That allows me to listen to javascript focus changes and hide/show the keyboard. This way I can make an overlay keyboard that is only visible when I click in a textfield which I find is a very nice solution. So this is how I listened to the javascript events ( keep in mind that this is all actionscript ):

// register everytime the page has loaded!
private function onPageLoaded( e:Event ):void {
  webView.window.addEventListener( "focus", onJavaScriptFocusIn, true );
  webView.window.addEventListener( "blur", onJavaScriptFocusOut, true );
 }

// if we get a focus in event from js, check if its a inputfield or a textarea. then show the keyboard.
private function onJavaScriptFocusIn( e:Object ):void {
  if( e.target.localName == "input" || e.target.localName == "textarea" ) {
    dispatchEvent( new JavaScriptEvent( JavaScriptEvent.FOCUS_IN ) );
  }
}

// we lost focus - hide keyboard
private function onJavaScriptFocusOut( e:Object ):void {
  dispatchEvent( new JavaScriptEvent( JavaScriptEvent.FOCUS_OUT ) );
}

With all this you can build your onscreen keyboard that is working in flash as in html. I made a quick flexbuilder air project that you can download with a keyboard, textfield and htmlloader.

Dynamic XML definitions 0

Oct13

Something that I haven’t noticed for a long time are dynamic xml definitions. What it is; Its a very easy way to construct xml with dynamic content. Here is a short example:

var nodeValue:String = "bis naii";
var attributeValue:String = "mich";
var xml:XML = <speech speaker={attributeValue}>{nodeValue}</speech>;
trace( xml ); // <speech speaker="mich">bis naii</speech>

The {} braces are replaced by the variable value. You can also place more complex stuff inside these curly braces. Here is another example:

var xml:XML = <root />
for ( var i:Number = 0; i < 3; i++ ) {
    xml.appendChild( <child>{"content: " + ( i + 1 )}</child> );
}
/**
 * gives:
 * <root>
 * <child>content: 1</child>
 * <child>content: 2</child>
 * <child>content: 3</child>
 * </root>
 */

In some situations this way of constructing an xml structure is very practical….

For more infos check senocular’s page about XML

Error #2148 or how to access local and network resources 4

Sep29

I bet you all got already the Error #2148 when developing. In my case this happens often when I am developing an application where some resources are local and some are already from a backend server. For example I have a local config.xml just right next to my swf application and some other data from a backend server somewhere on another domain.

Now this is a problem as you can either publish your swf with local-security sandbox or network-security sandbox but in my case I need both as I have local resources and network resources. So I go through both ways;

local-security sandbox way

local-sandbox-popup

I can access my config.xml but when I try to load the data from another domain the following popup shows up:

In the Security Settings Manager that opens when you click Settings… you can add the remote domain and restart the browser then the swf should be able to access this domain. But I personally prefere the network-security sandbox way:

network-security sandbox way

Here you publish your swf with the network-security sandbox by adding the -use-network=true to the flex compiler or setting the Local playback security to Access network only in the Flash CS4 publish settings. This way your swf can access any domains from the internet. So in my case no problem to load the data from my backend server. But when load my local config.xml I get the following error:

Error #2148: SWF file file:///demo.swf cannot access local resource config.xml. Only local-with-filesystem and trusted local SWF files may access local resources.

The fastest solution to get rid of this error you go to the Security Settings Manager and add a new location for mac: / and for pc: c:/

security_settings

The Security Settings Manager is a bit buggy. So restart your browser and check again if its really saved. Finally this entry allows the swf file to read local files. Here you allow full access to your machine which can be a security problem. It’s better to specify the root folder of your flash/flex projects. This way all your projects swf are trusted and can access all files in the subfolder of your flash/flex projects folder.

Thanks to a hint of nada there is a way to come around of the buggy Security Settings Manager. You can add a new cfg file in the FlashPlayerTrust directory (win: C:\windows\system32\Macromed\Flash\FlashPlayerTrust | mac: /Library/Application Support/Macromedia/FlashPlayerTrust ) and add your trusted folders in this cfg file. So my config file:

/Library/Application Support/Macromedia/FlashPlayerTrust/flexprojects.cfg

contains one single path to my flex projects:

/Users/mich/Flex Projects

And all my projects have access to local resources that are in this folder or in subfolders. One entry and you dont have to worry about any local access restrictions.

Summary

Both ways you are able to access both local and network resources. The advantage of the network-security sandbox way is that you have to add an entry only once and not every time you access a new domain. Specially if you set it up with your root flex/flash projects folder all your projects have automatically access.

TextField, StyleSheet and TextFormat 1

Sep21

I’m sure that everybody that ever try to apply a stylesheet to a textfield in Flash encountered some problems. Thats why I though I will write a summary about the workaround that I found so far.

First thing to know is how flash can apply css on text. If you set for example:

textField.text = "Hello is it <b>me</b> you <h1>looking</h1> for.";

You can style the text between tags here: <b>..</b> and <h1>…</h1> if you define css definition for these tags. An example css file would look like:

b {  font-weight: bold; }
h1 {  size:16; }

and the corresponding as source to set the styleSheet would be:

private function onLoaded( e:Event ):void {
// The TextLoader is a class from the indieas library
var loader:TextLoader = e.target as TextLoader;
var css:StyleSheet = loader.getDataAsCSS();
textField.styleSheet = css;
textField.text = "Hello is it <b>me</b> you <h1>looking</h1> for.";
}

Here its important that you set the text property after setting the styleSheet otherwise it will not apply the styles.

So far everything works as expected but what if you also want to style the normal text without any tags. You could wrap the text content in another tag like:

<text>Hello is it <b>me</b> you <h1>looking</h1> for.</text>

But thats not very handy instead we use the TextField own property defaultTextFormat. We can transform a css into a TextFormat and apply that as defaultTextFormat like this:

var styleObject:Object = css.getStyle( "*" );
var defaultStyle:TextFormat = css.transform( styleObject );
textField.defaultTextFormat = defaultStyle;
textField.styleSheet = css;
textField.text = "Hello is it <b>me</b> you <h1>looking</h1> for.";

Again here the order of applying defaultTextFormat, styleSheet and text is important. If you have a styleSheet applied and you want to set the defaultTextFormat it will throw an error. So if you want to reapply the defaultTextFormat do it like this:

var style:StyleSheet = textField.styleSheet; // save the styles to reapply them later
textField.styleSheet = null; // set this null to allow seting the defaultTextFormat
textField.defaultTextFormat = // new format;
textField.styleSheet = style; // reapply styles
textField.text = textField.text; // reapply text

The last thing to mention is the textField.condenseWhite property. Very often you load your content from an xml file and like to show a node content in a textField. But as the xml itself has linespaces and breaks the shown text is weird formatted. To avoid this use textField.condenseWhite = true. To make a new line just add a <br/> tag to your xml content and make sure your textfield has multiline set to true.

Summary:

  • use defaultTextFormat for default text style.
  • transform the defaultTextFormat from a StyleSheet style.
  • properties set order: defaultTextFormat, styleSheet, text.
  • set condenseWhite = true when setting xml content to the texfield.

To play around download a demo FlexBuilder project here.

Another Flash-FlexBuilder workflow: The Draft 3

Sep15

After my introduction article about my workflow I like to dig in a bit deeper and describe you my way of working with Flash and Flex. So far we have the assets ready to use but we need to add functionality to the assets so how do we join these to things together. One approach would be to extend from the exported MovieClip. So in my example that would be:

package {
 public class ControllBar extends ControllerBarDraft {

 public function ControllBar() {
 super();

 playButton.alpha = 0.5;
 }
 }
}

This way we have all assets on the timeline ready to use. Nothing more to do. But there is one major drawback. What when we want to extend from another class that from our exported MovieClip? You maybe think this happens not that often – but it does – so we can use this approach.

Luckily there is another way to come around that problem. We can simply instantiate the ControllerBarDraft (exported from Flash through swc) and copy the assets to our main class. That would look something like this:

package {
 import flash.display.SimpleButton;
 import flash.display.Sprite;

 public class ControllBar extends Sprite {

 public function ControllBar() {
 super();

 var cbd:ControllerBarDraft = new ControllerBarDraft();
 var playButton:SimpleButton = cbd.removeChild( cbd.playButton );
 addChild( playButton );
 }
 }
}

This is pretty cumbersome to do that for everything placed on the ControllerBarDraft MovieClip so I was looking for a way to do that automatically. And I ended up with a simple but powerfull Draft class. The core is this method:

public static function copyAssets( from:DisplayObjectContainer, target:DisplayObjectContainer ):* {

 while ( from.numChildren > 0) {

 var current:DisplayObject = from.removeChildAt( 0 );
 target.addChild( current );
 }

 return from;
 }

This preserves the z-order but more important it copies the whole DisplayObject with its blendMode, filters, colorTransformations etc.  It also copies normal shapes that you draw in Flash on the timeline. Simply it just copies everything into your class that you will work on. The code with the Draft class looks like this:

package {
 import flash.display.Sprite;

 import org.indieas.util.Draft;

 public class ControllBar extends Sprite {

 public function ControllBar() {
 super();

 var draft:ControllerBarDraft = Draft.copyAssetsFromClass( ControllerBarDraft, this );
 }
 }
}

So the assets are in place on your ControllerBar class but you probably need a reference to the playButton that you put inside the ControllerBarDraft thats why you get back this draft reference. To get the playButton you have now autocomplete on the draft instance as you see:

Picture 13

So you can now decide if you need a reference as an attribute in your class or if you just have to setup a listener or do something once in the constructor as the following example shows:

package {
 import flash.display.SimpleButton;
 import flash.display.Sprite;
 import flash.events.MouseEvent;

 import org.indieas.util.Draft;

 public class ControllBar extends Sprite {

 private var playButton:SimpleButton;

 public function ControllBar() {
 super();

 var draft:ControllerBarDraft = Draft.copyAssetsFromClass( ControllerBarDraft, this );
 playButton = draft.playButton;

 draft.stopButton.addEventListener( MouseEvent.CLICK, onStop );
 }
 }
}

This is now already very handy but as I have the Draft class I added some more functionality. I personally like the fact that I do the design part in Flash and the coding in FlexBuilder. But I am not a big fan of setting up position and width/height for everything I do by code. So I though that can do the Draft class for me and I added a method like this:

package {
 import flash.display.Sprite;

 import org.indieas.util.Draft;
 import org.indieas.widgets.scrollbar.ScrollBar;

 public class ControllBar extends Sprite {

 public function ControllBar() {
 super();

 var draft:ControllerBarDraft = Draft.copyAssetsFromClass( ControllerBarDraft, this );

 var scrollBar:ScrollBar = Draft.replaceAsset( draft.playButton, ScrollBar );
 }
 }
}

Now this is replacing my draft element “playButton” with a new instance of a ScrollBar class. The width, height, x, y and so on is automatically applied. What this allows you is to put placeholders in your design and swap them later with our DisplayObject classes you like. You can think of a design where you need a TextArea and some other visual elements around. You use a simple box as a placeholder where the TextArea should belong and export that and replace the placeholder with the TextArea class with the help of the Draft class. If there are design updates you dont have to change anything in your code you simple just adjust the placeholder in your MovieClip and hit CTRL-ENTER to update the swc.

So far I very happy with this workflow because it allows me to have full controll over my class – what I need as attribute – but also hide the elements I dont need. Something that I forgot to mention so far is the fact that you can work easily with multiple people on one project when they have their own fla files and export their swc’s.

If you like to play around with the Draft class you can either download the demo flex project or download our indieas library where you have also more stuff to explore.

Another Flash-FlexBuilder workflow: The basics 1

Sep14

You probably remember the mtasc compiler from the old AS2 times. One major benefit was the speed because it didnt compile the graphic assets all over again. With a right setup you can archive the same thing with Flash and Flex.
The key is the swc export feature of the Flash IDE:

Picture 8

If you export your MovieClips from Flash as Classes:

Picture 9

and add the swc in the Flex Builder as library:

Picture 10

you can access/create them by simply create a new instance:

Picture 12

You have to recompile (ctrl-enter in flash) the swc when you change something in your graphic assets. But in the FlexBuilder if you compile it just recompiles the source and includes the assets from the swc.
This workflow looks great in the first moment because you have autocomplete and strict typed access to the assets on the ControllerBarDraft. If you like to play around with the setup I made a simply actionscript FlexBuilder project that you can download here.

To use this workflow in an more advanced way, wait for the next article: Another Flash-FlexBuilder workflow: The Draft. Where I describe problems of this workflow as a nice workaround. Stay tuned.

Reinvent the wheel or how to program a button in AS3 1

Sep12

Something that you learn at the very beginning of developing flash projects is how to create a button. There is this practical Button symbol where you can define the common up, over and down states of a button. This is great but has two major downsides:

  1. you can not change anything at runtime like a label.
  2. there is no disabled state.

So I started to find a way to solve this. After a day playing around I came up with the following solution;

As it needs different states I was looking for a solution to encapsulate these states behind a single class and the StateManager was born. I setup the StateManager first with all the different states:

stateManager = new StateManager();
stateManager.addState( "up", ButtonUpDraft ); stateManager.addState( "down", ButtonDownDraft );
stateManager.addState( "over", ButtonOverDraft );

ButtonUpDraft, ButtonDownDraft, ButtonOverDraft are simple MovieClips exported from Flash that are instantiate inside the StateManager. Each one of these MovieClips contain a MovieClip called “bg” and a TextField called “label”. So to adjust for example the width of the “bg” on every state I can call:

stateManager.bg.width = 230;

To change the current state I simply can call:

stateManager.state = "up";

This way my Button class has not to deal with the individual states and can adjust properties of state assets over multiple states with one command. So my final Button class looks something like this:

package org.indieas.widgets {
 import flash.events.MouseEvent;
 import flash.text.AntiAliasType;
 import flash.text.TextFieldAutoSize;

 import org.indieas.theme.ButtonDisableDraft;
 import org.indieas.theme.ButtonDownDraft;
 import org.indieas.theme.ButtonOverDraft;
 import org.indieas.theme.ButtonUpDraft;
 import org.indieas.widgets.states.AbstractStatesWidget;

 public class Button extends AbstractStatesWidget {

 private var deltaWidth:Number;
 private var _resizeByLabel:Boolean = false;

 public function Button() {
 super();

 stateManager.state = "up";

 deltaWidth = stateManager.bg.width - stateManager.label.width;

 stateManager.label.autoSize = TextFieldAutoSize.LEFT;
 stateManager.label.multiline = false;
 stateManager.label.wordWrap = false;
 stateManager.label.mouseEnabled = false;

 addEventListener( MouseEvent.MOUSE_UP, onUp );
 addEventListener( MouseEvent.MOUSE_OVER, onOver );
 addEventListener( MouseEvent.MOUSE_OUT, onOut );
 addEventListener( MouseEvent.MOUSE_DOWN, onDown );

 useHandCursor = buttonMode = true;
 }

 protected override function initStates():void {
 stateManager.addState( "up", ButtonUpDraft );
 stateManager.addState( "over", ButtonOverDraft );
 stateManager.addState( "down", ButtonDownDraft );
 stateManager.addState( "disable", ButtonDisableDraft );
 }

 public function set label( value:String ):void {
 stateManager.label.text = value;
 if( _resizeByLabel ) {
 width = stateManager.label.width + deltaWidth;
 } else {
 width = stateManager.bg.width;
 }
 }

 public function get label():String {
 return stateManager.label.text;
 }

 public function set enable( value:Boolean ):void {
 mouseEnabled = mouseChildren = value;
 if( value ) {
 stateManager.state = "up";
 } else {
 stateManager.state = "disable";
 }
 }

 public function get enable():Boolean {
 return stateManager.state != "disable";
 }

 public override function set width(value:Number):void {
 stateManager.bg.width = value;
 stateManager.label.x = ( value - stateManager.label.width ) / 2;
 }

 public override function set height(value:Number):void {
 stateManager.bg.height = value;
 stateManager.label.y = ( ( value - stateManager.label.height ) / 2 ) + 1;
 }

 private function onUp( me:MouseEvent ):void {
 stateManager.state = "over";
 }
 private function onOver( me:MouseEvent ):void {
 stateManager.state = "over";
 }
 private function onOut( me:MouseEvent ):void {
 if( enable ) stateManager.state = "up";
 }
 private function onDown( me:MouseEvent ):void {
 stateManager.state = "down";
 }
 }
}

The advantage is obvious as there is no big mess with different states and you can focus only on the functionality of the button. So at the end of the day a friend, how had nothing to do with as, asked me what i was doing today. My answer was in a way disappointing as I said I just programmed a button… the whole day.

Problem with TextField.textWidth/TextField.width 2

Aug31

The problem:

Recently I struggled over another problem with the TextField where the textWidth / width was not calculated right.

Picture

On the screenshot you can see textfields stacked from the left to the right corresponding to the width of the textfield. If you look closely to the borders you see that the leading and tailing spaces around the words are not equal at all. Especially at the word “Newsletter” the tailing space too small. The texfield was setup like this;

label.autoSize = TextFieldAutoSize.LEFT;
label.wordWrap = false;
label.multiline = false;
label.antiAliasType = AntiAliasType.ADVANCED;
label.gridFitType = GridFitType.PIXEL;
label.embedFonts = true;
label.border = true;
var test:TextFormat = new TextFormat();
test.kerning = true;
test.font = "Futura";
label.setTextFormat( test );

The solution:

It seems that this is a flash bug and you can get over this by changing the GridFitType.PIXEL to GridFitType.SUBPIXEL.
The resulting textfields look like this;

Picture 1

Developed by Dariusz Siedlecki and brought to you by FreebiesDock.com