Auto size button for Flash components
I’ve recently been working outside of Flex in standard Flash & Actionscript, so I thought I’d take the opportunity to try the CS3/4 components. They’re much leaner than their bigger brother’s, and as a consequence don’t offer anywhere near the functionality, but their simplicity means they’re fast and easy to work with.
One of the tweaks I had to make was creating an auto-sizing Button:
If you type some text into the box you can see the difference. The standard Button doesn’t change it’s width based on the label length, which is crucial to any web project if it’s multi-lingual. So here’s my solution, with both an example and the code.
Code
In order to add the auto-sizing functionality I needed to subclass Button and override the layout routine. I also added a property that allows you to turn the auto-sizing on of off, the default is on.
{
import fl.controls.Button;
import fl.core.InvalidationType;
import flash.text.TextFieldAutoSize;
public class AutoSizeButton extends Button
{
public function AutoSizeButton()
{
super();
}
protected var _autoSize:Boolean = true;
/**
* Whether auto sizing is turned on. Default is true.
*/
public function get autoSize():Boolean
{
return _autoSize;
}
public function set autoSize(value:Boolean):void
{
_autoSize = value;
textField.autoSize = _autoSize ? TextFieldAutoSize.LEFT
: TextFieldAutoSize.NONE;
invalidate(InvalidationType.SIZE);
}
override protected function drawLayout():void
{
if (autoSize)
{
// Set the component width by
// calculating text & padding widths
var txtPad:Number =
Number(getStyleValue(“textPadding”));
_width = (textField.textWidth + 4) + (2 * txtPad);
}
super.drawLayout();
}
}
}
Basically all this class is doing is intercepting the layout drawing routine and pre-calculating the entire component width. Then it calls super.drawLayout() which ensures the text field sizes to the width. The calculation is taken directly from LabelButton, a super class of Button.
Issues
There are a few issues: Firstly it won’t work with an icon in the button, and secondly it doesn’t auto-size the height. Also you will need to instantiate it through Actionscript, like so:
myButton.label = “My first button”;
addChild(myButton);
Download source code here: AutoSizeButton.as
Posted: April 19th, 2009 under Flash.
Comment from jcfrog
Time May 2, 2009 at 12:56 pm
Thnks a lot!!
I just added a getAutoWidth function because I was not able to get the real width of the dynamic new AutoSizeButton.
public function getAutoWidth(){
// text & padding widths
var txtPad:Number =
Number(getStyleValue(”textPadding”));
return (textField.textWidth + 4) + (2 * txtPad);
}
override protected function drawLayout():void
{
if (autoSize)
{
_width = getAutoWidth() ;
}
super.drawLayout();
}
Thanks again!