Friday, November 11, 2011

Problem with updating SDK in Flash builder - Flash player version

I've added another version of  SDK to my Flash builder. It's easy as CTRL+C, CTRL+V. But afterwards my projects were complaining that they don't see flash player and throws error with playerglobal.swc in it's title.

I have to mention that I was switching from sdk 3.5 to 4.1 so automatically I had to upgrade player form version 9 to 10.

In my project properties I had unchecked generating html site with embedded flash like on screen below. I thought if it is disabled IDE is not taking this into consideration. WRONG!
When I:

  1.  selected "Generate HTML wrapper file"
  2. put new version of flash player (10.0.0 instead of 9.0.124)
  3. pressed "Apply"
  4. unselected "Generate HTML wrapper file"
Errors dissapeared.

One more thing. I'm not using html wraper file. I'm not sure how it works when you have it selected. Maybe it'll update automatically. If not do it manually but with ommiting points 1 and 4 from my list.

Monday, October 3, 2011

HTML tags in textfield

If you want to format text in field using old html tag here is simple list of possible tags:


  • <a> hyperlink. Has two parameters:
    • target - target window
    • href - url  (or event!)
  • <b> - text betwen those tags will be bold
  • <br> - breaks line
  • <font> - describes font:
    • color - color of the text. Must be in hex (with # at the begining)
    • face - font name
    • size - font size
  • <img>  allows to embed image (or swf) like in html site. Here is a list of supported properties:
    • src - source of media
    • width - width of rectangle where media is placed (always in px)
    • height - height of rectangle where media is placed (always in px)
    • align - horizontal alignment. Left or right. Specifies on which side text will flow around the image
    • hspace - horizontal margin around media. By default it is 8px
    • vspace - vertical margin around media. By default it is 8px
    • id - identifier for embedded media. Used to controll it
    • checkPolicyFile - connected to the security policy. Used with flash swf file embedded
  • <i> - text between those tags will be italic. 
  • <li>, <ul>, <ol> - lists. ordered and dotted
  • <p> - paragraph. Supports only two attributes:
    • align - specifies if text block is aligned to left/right/center or justify
    • class - connects with CSS class
  • <span> - inline part of text that allows only one attribute:
    • class - classname from CSS
  • <u> - text between those tags will be underlined

Thursday, September 1, 2011

Disabling Textfield scrolling


This tip is probably only for my own memory.

When you want to disable scrolling multiline textfield by mouse wheel use this:

myTextField.mouseWheelEnabled = false;

that's all folks!

Wednesday, August 17, 2011

One image, three states of button.


When we want to create custom button, usually three states considered: mouse over (roll over), mouse out (roll out) and press (click, release). If it is advanced, with multiple animations, and differences between those free states, theres no other way to create each of them separately. But if You need quite simple button which changes its color, look at this example.

Firstly some declarations:

private var _loader:Loader;


private var _colorTransform:ColorTransform;
private var _rollOverColorTransform:ColorTransform;
private var _clickColorTransform:ColorTransform;
        
private var _color:uint;
private var _rollOverColor:uint;
private var _clickColor:uint;

We also have to define values:

_color = 0xFFFFFF;
_rollOverColor = 0xFF6600;

We load image:

_loader = new Loader();
_loader.load(new URLRequest(url));
addChild(_loader);
buttonMode = true;

Prepare transformations for switching states:

_colorTransform = _loader.transform.colorTransform;
_colorTransform.color = _color;
_loader.transform.colorTransform = _colorTransform;
            
_rollOverColorTransform = _loader.transform.colorTransform;
_rollOverColorTransform.color = _rollOverColor;


_clickColorTransform = _loader.transform.colorTransform;
_clickColorTransform.color = _clickColor;

Then we set listeners:

addEventListener(MouseEvent.ROLL_OVER, handleRollOver);
addEventListener(MouseEvent.ROLL_OUT, handleRollOut);
addEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);

And handlers for events:


private function handleRollOver(e:MouseEvent):void
{
    _loader.transform.colorTransform = _rollOverColorTransform;
}
    
private function handleRollOut(e:MouseEvent):void
{
    _loader.transform.colorTransform = _colorTransform;
}
        
private function handleMouseDown(e:MouseEvent):void
{
    _loader.transform.colorTransform = _clickColorTransform;
}

And it's done!

Check it:




Saturday, August 6, 2011

Letter Spacing - TextFormat or css StyleSheet

If you;re looking for example of setting letter spacing - here it is.

The first solution is TextFormat. The property is named same in both options - letterSpacing. Let's see the code:

var txtfmodified:TextField = new TextField();
addChild(txtfmodified);
txtfmodified.y =20;
txtfmodified.text = 'hello world';
var tf:TextFormat = txtfmodified.getTextFormat();
tf.letterSpacing = 3; /* I tried lots of different values here. */
txtfmodified.setTextFormat(tf);

We can also use stylesheet to adjust part of text (in previous solution you can also adjust part of text but selecting chars is more complicated than using styles for classes of html tags). Here is the example:

var txtfmodified2:TextField = new TextField();
addChild(txtfmodified2);
txtfmodified2.y =40;
txtfmodified2.text = 'hello world';
var s:StyleSheet = new StyleSheet();
s.setStyle("p", {letterSpacing:3});
txtfmodified2.styleSheet = s;
txtfmodified2.htmlText = "<p>hello world</p>";

Remember that there are two solutions but you cannot mix them. Either way you'll receive error like this:
Error: Error #2009: This method cannot be used on a text field with a style sheet


And a proof at the end. First line is simple not modified field. Second line is modified by TextFormat properties. Third line is adjusted by stylesheet.




Tuesday, August 2, 2011

Color in Hex and separated to RGB channels

I don't know why conversion between hex code of color and separating it into RGB channels is not built in AS3.0 classes. It's quite easy operation. Here are methods for both directions:

function hex2RGB ( hex:Number ):Object 
{
var rgb:Object = new Object();
rgb.r = (hex & 0xff0000) >> 16;
rgb.g = (hex & 0x00ff00) >> 8;
rgb.b = hex & 0x0000ff;
trace(rgb.r, rgb.g, rgb.b);
return rgb;
}


Usage:
hex2RGB(0xE60E3F); // 230, 14, 63

It's more functional to operate on one object so the function returns it. For testing purpose there is trace that prints values of channels

function RGB2hex (r:uint, g:uint, b:uint):Number
{
return ((r << 16) + (g << 8) + b);
}

Usage:
trace(RGB2hex(230, 14, 63).toString(16));
For displaying purpose the radix has been changed to 16 (hex)

Monday, July 11, 2011

Dynamic Font Embedding

When You want to load some parts or modules later font is one of thing that is not most important. Sometimes there is some kind of configuration where you or user chooses which font should be used. In those situations font should be embedded dynamically. So here simple instruction step by step:

Firstly we need font packed separately in swf. I made sepataed project to easily maintain it but it can also be module. My code looks like this:


package Arial
{
import flash.display.Sprite;

public class Font_Arial extends Sprite
{
[Embed(source='ARIAL.ttf', fontName="Font_Arial", unicodeRange='U+0020-U+002F,U+0030-U+0039,U+003A-U+0040,U+0041-U+005A,U+005B-U+0060,U+0061-U+007A,U+007B-U+007E, U+00A0-U+00FF, U+0100-U+017E, U+20AC')]
public static var Font_Arial:Class;


[Embed(source='ARIALBD.ttf', fontWeight= "bold", fontName="Font_Arial", unicodeRange='U+0020-U+002F,U+0030-U+0039,U+003A-U+0040,U+0041-U+005A,U+005B-U+0060,U+0061-U+007A,U+007B-U+007E, U+00A0-U+00FF, U+0100-U+017E, U+20AC')]
public static var Font_ArialBold:Class;

[Embed(source='ARIALI.ttf', fontStyle='italic', fontName="Font_Arial", unicodeRange='U+0020-U+002F,U+0030-U+0039,U+003A-U+0040,U+0041-U+005A,U+005B-U+0060,U+0061-U+007A,U+007B-U+007E, U+00A0-U+00FF, U+0100-U+017E, U+20AC')]
public static var Font_ArialItalic:Class;

[Embed(source='ARIALBI.ttf', fontStyle='italic', fontWeight= "bold",fontName="Font_Arial", unicodeRange='U+0020-U+002F,U+0030-U+0039,U+003A-U+0040,U+0041-U+005A,U+005B-U+0060,U+0061-U+007A,U+007B-U+007E, U+00A0-U+00FF, U+0100-U+017E, U+20AC')]
public static var Font_ArialBoldItalic:Class;


}
}

Maybe small description of code. I have  got package name. This will be important later.
Class name is something you can sat as you wish. The only thing is that it cannot be named as Font name in system, so if you name it Arial there will be conflict.
As You can see I'm embedding similar files - each one consist different style - there is normal, bold, italic and bold&italic (last one is separated style!). For each one there are describing parameters fontWeight and fontStyle.
FontName for all font styles must be the same and must be same as class name.
Last parameter is unicodeRange. it describes which signs are embedded. You can leave it but then all signs will added which usually is unnecessary and your file will be heavy. For example all glyphs from Arial normal (without bold and italic) weights about 300kB when my file with four styles and only glyphs that are used by my application (latin symbols, numbers, special chars) weights 90kB.

Now let's load it

public function FontLoader():void {
loadFont(_serverPath+"fonts/Arial/Font_Arial.swf");
}


private function loadFont(url:String):void {
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, fontLoaded);
loader.load(new URLRequest(url));
}

I hope this part is easy and don't need comment


private function fontLoaded(event:Event):void 
{
var FontLibrary:Class = event.target.applicationDomain.getDefinition("Arial.Font_Arial") as Class;


Font.registerFont(FontLibrary['Font_Arial']);
Font.registerFont(FontLibrary['Font_ArialBold']);
Font.registerFont(FontLibrary['Font_ArialItalic']);
Font.registerFont(FontLibrary['Font_ArialBoldItalic']);


drawText();
}

We're extracting data from externall module. Remember my package name Arial? Full class name with package has to be put to getDefinition() method. Remember about package name. I lost some time to figure it out.
When you register font you can use it globally in your app.  Instead of calling similar command four time you can use foreach loop here.
Now we can use our font.

public function drawText():void
{
var tf:TextFormat = hintText.getTextFormat();

tf.font = "Font_Arial";
hintText.embedFonts = true;
hintText.setTextFormat(tf);
hintText.defaultTextFormat = tf;

}

I hope it's clear enough.

Tuesday, May 31, 2011

A lot of useless files in output folder

I was wondering why does flex builder (flash builder also) generates so many empty folders in my debug output folder. I found there whole structure of folders while they were empty cause they included only source files. I found that it's easy to clear it. In Poperties on ActionScript Compiler window you have to uncheck Copy non-embeddded files to output folder



Thursday, April 28, 2011

VerifyError: Error #1053: Illegal override of z in mx.core.BitmapAsset.

Have you ever got error like in title? I was wondering what's the problem. I've checked everything twice. Spent on this some time. Solution? Check version of flash player and SDK that you're using. I had Flash player 10.1, I was compiling to 9.0 but was using SDK 4.2

Sunday, April 17, 2011

link to page in new tab/window

Everybody hates popups and annoying ads. They usually cover site and try to open new site. So there are ad blockers, etc. But sometimes there's need for creating "polite" site that really needs to open new one.

I found this solution somewhere. Please use it for non-offensive cases.

To open new site (e.g. click n button in flash) we have to call javascript on site so it will create form and submit it on the fly.

ExternalInterface.call('(function (){var f = document.createElement("form");document.body.appendChild(f);f.style.display="none";f.setAttribute("target","_blank");f.setAttribute("method","POST");f.setAttribute("action","'+url+'");f.submit(); })()');


IMPORTANT!
The whole code from above must be in one line.
There's url variable inside. Put there your url that is need to be open.

Thursday, April 7, 2011

Cast vs as operator

I was wondering what's the difference between different types of casting. So I made some tests

var test1:Number;
trace( test1 as String); trace( test1.toString()); trace( String(test1));

//Output:
//null
//NaN
//NaN

OK, so we have two types casting. While 'as' returns us not defined String type (casted value also was not defined), standard casting creates instance that tries to use data casted type

Let's try the opposite way. But this time on defined instance

var test2:String = '100';  
trace( test2 as Number); 
trace( Number(test2));



//Output:
//null
//100

Casting give us instance with data gathered from base class. But 'as' operator one more time returns null. I wondered how does it work. And I found. Check this example:


var test3:Sprite = new Sprite(); 
trace( test3 as DisplayObject); 
trace( test3 as MovieClip);


Operator 'as' is concatenation of checking type of data and casting data. It casts only when base type is descendant of casted type. If expression is inherits casted class then it's returned. Otherwise it returns null

Sunday, April 3, 2011

From String to Boolean - casting problem

This is not a great discover, but sometimes it can help to save some time while wondering why there is true when should be false. I usually meet this situation while reading data from url GET parameters or from XML.

Let's check the example:



var stringTrue:String = 'true';
var stringFalse:String = 'false';


var boolDataTrue = new Boolean(stringTrue);
trace('#1 String true is casted to:', boolDataTrue);
//#1 String true is casted to: true


var boolDataFalse = new Boolean(stringFalse);
trace('#1 String false is casted to:', boolDataFalse);
//#1 String false is casted to: true



For this example I made two variables. In Boolean constructor ther's object as argument. But no matter what kind of string you put there it always deals it as 'true' expression

For quick and short fix you have to put there expresion that checks text and returns true or false as a proper type:


var boolDataTrue = new Boolean(stringTrue == 'true'?true:false);
trace('#2 String true is casted to:', boolDataTrue);
//#2 String true is casted to: true


var boolDataTrue = new Boolean(stringFalse == 'true'?true:false);
trace('#2 String true is casted to:', boolDataTrue);
//#2 String true is casted to: false


Wednesday, March 30, 2011

Adjusting SWF parameters for ActionScript Project

While creating ActionScript Project in Flex builder (Flash builder) You have no .fla file where it's possible to set background color or dimensions.

Eitherway it's possible to configure those settings. To define them add line like this:

[SWF(width="800", height="600", backgroundColor="#ffffff", frameRate="30")]

before main class definition.

Thursday, March 17, 2011

Sound in flash


Here is short tutorial how to play sound in flash and control it.

Firstly we need to import classes:

import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;

also one more for loading file:
import flash.net.URLRequest;

In this example file will be loaded externally. Of course there is possibility to embed it.

Now, we have to create instance and load file into it:

var mySound:Sound = new Sound();
mySound.load(new URLRequest('sound.mp3'));

Now it's time to play and control it. It's possible to initiate playing sound even if it's not loaded. Flash itself creates stream and buffers it automatically. It may happen that sound won't be played when you call play() method because it's not yet buffered enough:


var myChannel:SoundChannel = new SoundChannel();
myChannel = mySound.play();

Now we should stop it. Don't ask me why but you cannot stop sound but whole channel

myChannel.stop();

OK, let's go a bit further. Pause option. There's no ready solution. We have to stop channel. Remember to  save progress before.


pausePosition = myChannel.position;
myChannel.stop();

Position is value from 0 to 1 which holds the progress of played track. Now when we have this information we should modify play so that we can continue from saved moment instead of starting from begin.

myChannel = song.play(pausePosition);

While testing you 'll find that you need one more fix. Stop action should reset position


pausePosition = 0;
myChannel.stop();

Let's add one more thing. Volume control. ActionScript3 allows to configure almost every aspect of playing sound. Such complicated functionality needed many classes. That's why for modifing volume we use another class SoundTransform.


myTransform.volume+=VOLUMESTEP;
myChannel.soundTransform = myTransform;

Initially volume is set to 0.5 so you can switch it both ways.

Remember that every time you start playing sound it's sound's transformations are reseted. So to continue playing after pause with same volume level, you have to assign settings


myChannel = song.play(pausePosition);
myChannel.soundTransform = myTransform;







Friday, March 11, 2011

ADDED vs. ADDED_TO_STAGE

ADDED and ADDED_TO_STAGE are two events that are dispatched on object when this is added as child to displayed parent. But there is a reason why they both exist. Here is small study on differences.

Case #1 - adding object to stage.
in this case we're adding class (named A) to main class which is stage. both listeners are added as in presented code:

public class A extends Sprite
{
    public function A()
    {
        trace('A A()');
        super();

        addEventListener(Event.ADDED, _handleAdded);
        addEventListener(Event.ADDED_TO_STAGE, _handleAddedtoStage);
    }

    private function _handleAdded(event:Event):void
    {
        trace('A added');
    }

    private function _handleAddedtoStage(event:Event):void
    {
        trace('A AddedtoStage');
    }
}


And here is main class code:

public function Blog()
{
    trace('Blog Blog()');
    var a:A = new A();

    trace('adding A to stage');
    addChild(a);
}


Here is result of experiment:

Blog Blog()
A A()
adding A to stage
A added
A AddedtoStage


Conclusion: both events works works similar. What is more, everytime ADDED is before ADDED_TO_STAGE. Flash is not working parallely so there must be some reason of this constant order. If You switch adding listeners result is the same. This shows that ADDED is always dispatched before ADDED_TO_STAGE.

Case #2 - cascade adding objects to stage
Now we add one more object, so structure will look like this:

Stage(Blog) -> A -> B

Main class of Blog stays same as in previous example. Class A is modified to create instance and load into itself object of type B. Here is code of class A:

public class A extends Sprite
{
    public function A()
    {
        trace('A A()');
        super();

        addEventListener(Event.ADDED_TO_STAGE, _handleAddedtoStage);
        addEventListener(Event.ADDED, _handleAdded);

        var b:B = new B();
        addChild(b);
    }

    private function _handleAdded(event:Event):void
    {
        trace('A added');
    }

    private function _handleAddedtoStage(event:Event):void
    {
        trace('A AddedtoStage');
    }
}


And here we have source of class B. It looks like class A in previous case:

public class B extends Sprite
{
    public function B()
    {
        trace('B B()');
        super();

        addEventListener(Event.ADDED_TO_STAGE, _handleAddedtoStage);
        addEventListener(Event.ADDED, _handleAdded);
    }

    private function _handleAdded(event:Event):void
    {
        trace('B added');
    }

    private function _handleAddedtoStage(event:Event):void
    {
        trace('B AddedtoStage');
    }
}


And let's see what now happens:

Blog Blog()
A A()
B B()
B added
A added
adding A to stage
A added
A AddedtoStage
B AddedtoStage


Conclusion: First thing is that an event ADDED is captured in class A twice. Once when object is added to this class as child and once when the object itself is added to parent. Second and most important part delay between capturing those event. This shows that event ADDED is dispatched each time when method addChild (or AddChildAt) are called. And this event is dispatched first. ADDED_TO_STAGE is dispatched when object or it's parent or a structure of objects of many levels are added to displayed class on stage. And this event goes as second. Last thing - ADDED_TO_STAGE event is propagated from stage to it's children and to further levels of descendants


Thursday, March 10, 2011

Simple mask

Mask is a layer that covers our appropriate object. It is always problem what is mask and what is masked. And what should be on mask layer. So here is short description with example. Look at this schema:
From the right:
  • back - complete image that is covered
  • mask - objects and shapes here creates holes through which we see image from back
  • result - this is what we get as result of using mask
Background can be everything. In this example it's a simple image:

_background = new _BackGround();
addChild(_background);

Mask can be simple shape. If it's static it don't have to be added as child to stage. But if we want do some action on mask it's neccesary:

var mask:Sprite = new Sprite();
mask.graphics.beginFill(0xFF6600, 1);
mask.graphics.drawRect(-40, -40, 80, 80);
mask.graphics.endFill();
addChild(mask);
_background.mask = mask;
mask.startDrag(true);

In this example mask is a draggable square that follows mouse cursor. Check it!



Associative array

There no such thing like associative array in ActionScript. It would be too easy. In the other hand every object in AS3 is an associative collection of values. Here is example of how it works:

var assocArray:Object = new Object();

And that is all for creating. to set value we call setter

assocArray.price = 10000;

or more like aray

assocArray['price'] = 10000;

Reading looks similar:

assocArray.price

or

assocArray['price']

More complicated situation is with displaying full array. Trying to trace instance will cause something like this:

[object Object]

Also checking the size or length by variable of method doeas not help because returns zero. The easiest option is to create a for-each loop that displays all variables:

for (var item in assocArray)
{
    trace(item,' : ',assocArray[item]);
}

For counting elements the fastest solution is creating a loop that increments value for each item. But it's not good solution for big structures. In this situation good solution will be own class that controls records with push() and pop() methods.

Monday, February 28, 2011

9-scale resizing

If You want to create component properly scalable remember about resizing shapes. Problem occurs during resizing for example rectangles. Border of 2 pixels thick becomes really big. Because object is resized as-is proportionally with content and graphic.
Here is the proof:

To avoid this problem You should use 9-scale. This property (officialy named scale9Grid) is avaiable in Movieclips, Sprites and so on. Here is example of code how to use it:

var background3 = new Sprite();
background3.graphics.lineStyle(2, 0xd61e31);
background3.graphics.beginFill(0xFFFFFF, 1);
background3.graphics.drawRect(0, 0, 40, 40);
background3.graphics.endFill();


//here comes 9-scaling
var grid:Rectangle = new Rectangle(5, 5, 30, 30);
background3.scale9Grid = grid;


Rectangle that is created above creates 9 regions in our object (which also is rectangle shaped). Picture below shows regions. Points A(5,5) and B(30,30) shows coordinates of lines which are regions borders.


Those 9 regions can be grouped to 4 types. Each type is scaled in different way:
  • corners - four corners are not scaled. They are constant
  • long vertical sides - middle-left region and middle-right regions are scaled only in Y axis
  • long horizontal sides - center-top and center-bottom regions are scaled only in X axis
  • middle-center - this region is scaled in both directions

Here is description from API


Thursday, February 24, 2011

Embedding fonts

Embedding fonts is quite easy. Here is example:

Firstly, we have to embed font. In this case my path is relative. mimeType is not manatory, but it's good practise to fill it.

[Embed(source='assets/MyFont.ttf', fontName="Font_MyFont", mimeType="application/x-font-truetype")]
private static var stringForHoldingFont:String;

Variable from above is not used anywhere. It's just for holding glyphs.

Here comes our field, where we use embedded font
private var _title:TextField;

_title = new TextField();

var style:TextFormat =  _title.getTextFormat();

Type of font is set in TextFormat. We can create new or copy existing one. And here comes most important part. We set name from embed. And in textfield object (not TextFormat!), we setembedFonts property to true. Otherwise there will be no result.


style.font = "Font_MyFont";
_title.embedFonts = true;

When we set format for field this should work.


_title.setTextFormat(style);
_title.defaultTextFormat = style;

If You are using Flex builder / Flash builder as IDE remember to set font manager for project. Otherwise it won't work. To do this choose project properties -> 'ActionScript Compiler' and as 'Additional compiler arguments' put
 -managers flash.fonts.AFEFontManager 
like on this screen:

Remember to check it on device where this font is not installed. For example if You forget to set property embedFonts this will work on computer where you have this font (like probably your computer).



Tuesday, February 22, 2011

Setters and Getters

Similar to other programming languages like C# there is possibility to create setters and getters in ActionScript. Here is an example:

//method accesed privately
private var _title:String = "Title";


//getter
public function get title():String
{
    return m_title;
}


//setter
public function set title(aTitle:String):void
{

    _title = aTitle;

    /*
     * here can be other code that you need to be executed 
     * when somebody sets your variable
     * example:
     * this.dispatchEvent(new Event('ModelTitleChangeEvent'));
     */
}

Use it or not? It depends on You and Your project. If project is advanced it is useful solution. And in my opinion code is easy to understand.

Monday, February 7, 2011

Problem with xampp - why apache server does not start

While using xampp you can be faced with problem when apache server cannot start. Even if console window show info, the status and button does not change.
The problem is not in xampp itself but in another program on your computer that uses port 80. In my case it was skype. To turn it off in skype open Tools -> Options -> Tab 'Advanced' -> 'Connection' and uncheck 'Use port 80 and 443...'
Now just save and restart skype. Let's check results.
It works.

Friday, February 4, 2011

Text alignment

When positioning text there is easy way to set horizontal align like in this example:

_background = new Sprite();

_background.graphics.beginFill(112233,0.7);
_background.graphics.drawRect(0,0,200,20);

_itemLabel.width = _background.width;

rollOutStyle = _itemLabel.getTextFormat();
rollOutStyle.align = TextFormatAlign.CENTER;


another option is to switch last two lines by:


_itemLabel.autoSize = TextFieldAutoSize.CENTER;


But there is no such solution for vertical. We have to set it manually:


_itemLabel.y = _background.height * 0.5 - _itemLabel.textHeight * 0.5;

Thursday, February 3, 2011

Numerical attributes in XML & no value in code

I know it's a stupid case, but sometimes I forgot about simple things.

Problem:
we have numerical value in XML like:

<component itemHeight="20" itemsVSpace="10" .../>

in code we want to use those values

itemLabel.y = index*( _contentXML.@itemHeight + _contentXML.@itemsVSpace);

Result? We receive zero. Because attribute value is used as String and + works as concatenation. Then multiple converts value to zero. We have to cast values at the begining to expected type:

itemLabel.y = index*( int(_contentXML.@itemHeight) + int(_contentXML.@itemsVSpace) );

Wednesday, February 2, 2011

buttonMode & TextFields

We have some kind of like Sprite/MovieClip. We're creating our own button or item that should be click-able. So we set buttonMode, add event listener, and everything is ok till we add some text. And here comes problem. Hand cursor disappears when we roll over on the text.

best solution is to use mouseChildren property.

this.buttonMode = true;
this.mouseChildren = false;
this.addEventListener(MouseEvent.MOUSE_UP, _handleMouseRelease);

All objects added as child won't be mouse enabled