First, I needed a monospace (fixed width) font. You can embed your own fonts in a Flash SWF, but that was overkill for this effort. You could specify a specific font, such as 'Courier New' that is monospace. However, there can be issues if the client's device does not have the specific font face. Device Fonts often serve as a fallback font if the specific font requested does not exist on the user's device. In this case, I didn't want to select a specific font, I just wanted the default monospace font. So I used the _typewriter font (the other types are _sans and _serif).
<mx:text id="myText" fontfamily="_typewriter" />Once I had a monospace font, I needed to determine the proper size of the control for an 80x24 terminal. I started by simply setting the text control to an 80 character wide (and then 24 character high) string and noting the size, but I needed something that would work easily at runtime. I created this quick helper method that would resize my control:
private function setSize(control:mx.controls.Label, charWidth:int, charHeight:int, defaultText:String = "") : void {I set this method to be called when the container's creationComplete event fired. This method assumes that the control is set to an empty string initially, and accepts an optional defaultText parameter if you wish to initialize it.
var testString:String = "0";
var width:int = control.width + (control.measureText(testString).width * charWidth);
var height:int = control.height + (control.measureText(testString).height * charHeight);
control.text = defaultText;
control.width = width;
control.height = height;
}
The measureText method returns the size of the text, but not the surrounding control borders, so I added the default control size to the text size to achieve the proper control size.