Tuesday, May 13, 2008

Re-sizeable (Resizeable) Text Area for Flex 3 without scrollbar

Flex's TextArea class always uses a scrollbar to compensate for text too large to fit, but I wanted to find a way to resize without it. All of the examples that I found online that worked only took into account the height, so here's what I came up with to make the TextArea resize to a nice width to height ratio of 1.5 to 1:

*******************************************************************************
*******************************************************************************
IMPORTANT NOTE!! -- Blogger.com wouldn't let me post the content below without corrupting my CDATA tag. YOU'LL NEED TO ADD THE "!" back in at the appropriate place in the beginning CDATA tag (after the "<") for this example to work!
*******************************************************************************
*******************************************************************************





<[CDATA[
import mx.events.FlexEvent;

[Bindable]
private var myText:String;
[Bindable]
private var starSpangled:String = 'Oh, say, can you see, by the dawn\'s early light what so proudly we ' +
'hailed at the twilight\'s last gleaming?' +
'Whose broad stripes and bright stars, through the perilous fight, o\'er the ramparts we watched,' +
'were so galantly streaming?' +
'And the rockets\' red glare, the bombs bursting in air, gave proof through the night that our' +
'flag was still there. Oh, say, does that star-spangled banner yet wave o\'er the land of the free' +
'and the home of the brave?';

private function onCC():void
{
textArea.addEventListener(FlexEvent.UPDATE_COMPLETE, resizeTA);
myText = starSpangled;
}

private function resizeTA(e:FlexEvent):void
{
// Calculate the minimum area required.
var width:Number = textArea.width;
var height:Number = textArea.textHeight + 22;
var minRequiredArea:Number = width * height;

// Calculate how to get that with the desired ratio of width:height = 1.5:1
var ratio:Number = width/height;
while (!(ratio >= 1.5)) {
width += 1;
height -= 1;
ratio = width/height;
}
// Set the width and height to the new values.
textArea.explicitWidth = width;
textArea.explicitHeight = height;
textArea.removeEventListener(FlexEvent.UPDATE_COMPLETE, resizeTA);
}

]]>