Color name to uint value

Filing under the “why didn’t I find this before” folder. On the Adobe Flex forums, there was a question about changing the color value of a button based on a switch statement. The user was trying to change the value to “Red”, “Yellow” or “Green”. In the button, the type for color is uint value, so the input needs to be something like “0×990000″ for “Red”. I usually just insert in the uint value for a color and not the name, since I usually have to change it. But, this question on the forum got me thinking and searching for an answer. The simple answer is the IStyleManager2, which allows you to get the uint value of a color name. Presto!

Here’s the reply to the user’s question that I have been attempting to post to the forum.


First set a declaration of the variable. I am setting the default value to Black in uint value.

<fx:Declarations> <fx:uint id="batteryStatusColor">0x000000</fx:uint></fx:Declarations>

This will allow you to bind it to your button parameter.

<s:Button id="Battery" x="791" y="513" width="124" height="46" 
label="Battery" fontSize="20" color="{batteryStatusColor}" />

Then, in your function, make sure you convert the String value of the color to a uint

private function changeBatteryStatusColor(batteryStatus:int):void {
	var tmpColorString:String = "Black";
	switch(batteryStatus)
	{
		case 1:                                                                                                                 
			tmpColorString = "Red";                                                                                          
			break;
		case 2:                                                                                                                 
			tmpColorString = "Green";
			break;
		default:                                                                                                                 
			tmpColorString = "Yellow";                                                                                                    
			break;                   	
	}   
	
	var newStyleManger:IStyleManager2 = StyleManager.getStyleManager(this.moduleFactory);	
	batteryStatusColor = newStyleManger.getColorName(tmpColorString);
}

The key part is the IStyleManager call that converts the String value of the color to a uint.

DataGrid Row Move

Another question on the Flex Forum about how to move a selected row on the DataGrid up or down, based on a button click.  The answer is straight forward, but with a catch.

When you click on the DataGrid, it will give you an index for the row you have clicked.  The first row in the DataGrid is 0.  If you wanted to simply move a row up and down the DataGrid, then you simply add or subtract 1 from the selected index.


// Move Item Up

SelectedIndex--;

// Move Item Down

SelectedIndex++;

Simple enough.  Unless you sort the DataGrid, which throws that out of wack and is pointless.  So, if you don’t plan on sorting the data, then adding a couple of buttons to move an item up and down within the DataGrid and the ArrayCollection provider, then here is the code.  It also includes checks to make sure you don’t move the item off ofthe grid.

Code for the Move Up Button


protected function moveUpBtn_clickHandler(event:MouseEvent):void
{
var upSelectedIndex:int = myDataGrid.selectedIndex;

// Move Item
if(upSelectedIndex > -1) {
if(upSelectedIndex > 0) {
// Get the selected Object
var moveObject:Object = myArrayCollection.getItemAt(upSelectedIndex);
// Get actual Object location if grid is sorted
var upActualIndex:int = myArrayCollection.getItemIndex(moveObject);
// Remove selected item at actualIndex
myArrayCollection.removeItemAt(upActualIndex);
myArrayCollection.refresh();
// Move both indexes
upActualIndex--;
upSelectedIndex--;
// insert item at actualIndex
myDataGrid.dataProvider.addItemAt(moveObject, upActualIndex);
myArrayCollection.refresh();
// select grid at selectedIndex
myDataGrid.selectedIndex = upSelectedIndex;
} else {
Alert.show("Item is currently at the top of the list.", "Move Alert",  Alert.OK, this);
}
} else {
Alert.show("No Item Selected.", "Move Alert",  Alert.OK, this);
}

}

Code for the Move Down Button


protected function moveDownBtn_clickHandler(event:MouseEvent):void
{
var downSelectedIndex:int = myDataGrid.selectedIndex;

if(downSelectedIndex > -1) {
// Move Item
if(downSelectedIndex < myArrayCollection.length -1) {
// Get the selected Object
var moveObject:Object = myArrayCollection.getItemAt(downSelectedIndex);
// Get actual Object location if grid is sorted
var downActualIndex:int = myArrayCollection.getItemIndex(moveObject);
// Remove selected item at actualIndex
myArrayCollection.removeItemAt(downActualIndex);
myArrayCollection.refresh();
// Move both indexes
downActualIndex++;
downSelectedIndex++;
// insert item at actualIndex
myDataGrid.dataProvider.addItemAt(moveObject, downActualIndex);
myArrayCollection.refresh();
// select grid at selectedIndex
myDataGrid.selectedIndex = downSelectedIndex;
} else {
Alert.show("Item is currently at the bottom of the list.", "Move Alert",  Alert.OK, this);
}
} else {
Alert.show("No Item Selected.", "Move Alert",  Alert.OK, this);
}

}

I did modify the DataGrid, so that the selectioMode is “singleRow”, which simplifies the selectedIndex information. I also set the selectedIndex for the row after the move, so the user can continue to move the row up and down and not have to select it again. Here is the example and source.

UPDATE: Had to set the Down Move to look for the Length of the ArrayCollection -1, because the DataGrid row starts at 0, it is one less than the total length of the ArrayCollection.

View Source

Column Chart with Item Renderer – updated

Okay, it didn’t take me long to get back and do some more fiddling with the Column Chart Item Renderer. I went ahead and changed the static ArrayCollection to a dynamic one, because I was trying to figure out something with Themes and needed a button and the button should do something. The ArrayCollection is fairly simple for this chart, so all I did was create a couple of random values from 0 to 100 and made the “date” value the counter time 10. I set it up so that you can press a button and create new data, which is helpful to see the changes to the columns.

// Create some random data for Yesterday and blank data for today
private function dataCreation():void {
	currentArray.removeAll();

	for(var h:int = 0; h < 4; h++) {
		// Generate Random Data
		var randomClose:Number = Math.floor(Math.random() * 100);
		var randomOpen:Number = Math.floor(Math.random() * 100);
		// create a temporary object and add the three values
		var tmpObject:Object = new Object();
		tmpObject.date = (h + 1) * 10;
		tmpObject.close = randomClose;
		tmpObject.open = randomOpen;

		// insert new tmpObject
		currentArray.addItem(tmpObject);
	}

	// Refresh the data
	currentArray.refresh();
}

After that was fixed, I went ahead to modify the ItemRenderer again, but this time to use a GradientFill and a BitMapFill. I had to reduce what was defined for the rectangle, to just a Graphic item as a holder.

s:Graphic id="graphicHolder" />

And then I declared three different rectangles, one for each type of fill. Again, this was to simplify things and also to make sure I was doing the right thing for each fill. As you can see in the Gradient Fill, I had to set the three GradientEntry items to create the look I need. You could do this all dynamically, but I don’t think most people will try different Gradients for each column. Which is why my Gradient fill only changes the Start, Mid and End color of the Gradient.

<fx:Declarations>
	<s:Rect id="imageRect">
		<s:stroke>
			<s:SolidColorStroke id="rectImageStroke" />
		</s:stroke>
		<s:fill>
			<s:BitmapFill id="imageRectFill" fillMode="repeat" scaleX=".70" scaleY=".70" smooth="true" />
		</s:fill>
	</s:Rect>

	<s:Rect id="gradientRect">
		<s:stroke>
			<s:SolidColorStroke id="rectLinGradStroke" />
		</s:stroke>
		<s:fill>
			<s:LinearGradient id="rectLinGrad">
				<s:entries>
					<s:GradientEntry id="linGradColorStart" ratio="0" alpha=".5" />
					<s:GradientEntry id="linGradColorMid" ratio=".25" alpha=".5" />
					<s:GradientEntry id="linGradColorEnd" ratio=".66" alpha=".5" />
				</s:entries>
			</s:LinearGradient>
		</s:fill>
	</s:Rect>

	<s:Rect id="solidRect">
		<s:stroke>
			<s:SolidColorStroke id="rectSolidStroke" />
		</s:stroke>
		<s:fill>
			<s:SolidColor id="rectSolidColor" />
		</s:fill>
	</s:Rect>	
</fx:Declarations>

From here, it was just setting the color for the Gradients and the appropriate image for the BitMap Fills. Except that it took me a while to figure out the correct syntax for the Image. I couldn’t declare it. I couldn’t just Embed it as the source. I had to Embed it as a Bindable Class and then set the BitmapAsset to that Class and finally make it the source for the BitMapFill.

// Embed the Red Apple Image
[Embed(source="../assets/images/red-apple.png")]
[Bindable]
public var imgRedApple:Class;

// Red Image Fill
var imgRedAppleObj:BitmapAsset = new imgRedApple() as BitmapAsset;
imageRectFill.source = imgRedAppleObj;

I simplified the code so that different columns do only two fills. I had columns doing all three fills, but decided that was too much code and could get really confusing. With the example below;

  • If the 1st column has more than 45, then the Red Apple Image Fill is used, else the Red Gradient Fill
  • If the 2nd column has more than 45, then the Blue Gradient Fill is used, else the Blue Solid Fill
  • If the 3rd column has more than 45, then the Green Apple Image Fill is used, else the Green Solid Fill
  • If the 4th column has more than 45, then the Purple Solid Fill is used, else the Purple Gradient Fill

I created a second file for this example, so that the first example and this example could be viewed separately.
View Source

[kml_flashembed publishmethod="dynamic" fversion="11.0.0" movie="http://deanlogic.com/demo/Flex/SimpleCharts/SimpleCharts2.swf" width="800" height="500" targetclass="flashmovie"/]

Column Chart with Item Renderer

When doing the Column Chart with fillFunction for a question in the Flex Forum, the poster said that he was trying to do something a little different. Instead of a simple fill, he wanted the fill to be semi-transparent with a solid border. When I looked at the iFill function, it didn’t have a stroke option and it doesn’t seem that the standard column item deals with the column border. My guess was, that an item renderer should be used for the column instead. Within the item render, you can create a rectangle graphic and then adjust the border and fill parameters. Since this seemed like an interesting exercise, I decided to make myself an example (the best way I learn something).

I started out using the simple array data found in other examples. I will probably update this to something more dynamic later.

[Bindable]
public var SMITH:ArrayCollection = new ArrayCollection([{date:10, close:41.87, open: 30},{date:20, close:45.74, open: 40}, 
{date:30, close:42.77, open: 60}, {date:40, close:48.06, open: 50}]);

And then I attached this to a ColumnChart and create a single ColumnSeries with the “date” on the xAxis and the “close” count on the yAxis. I then added the itemRenderer parameter, which popups a window for creating the component.

<mx:ColumnChart id="myColumnChart1" dataProvider="{SMITH}" >
	<mx:horizontalAxis>
		<mx:CategoryAxis categoryField="date" />
	</mx:horizontalAxis>
	<mx:series>
		<mx:ColumnSeries id="columnSeries1" xField="date" yField="close" itemRenderer="components.myColumnRenderer" />
	</mx:series>
</mx:ColumnChart>

In the ItemRender, the way to kick everything off is to override the set data function. You have to check to see if the value is null first, or you get errors when the chart is initially loading. Once there is data in the value, then you can start altering the renderer for the column.

override public function set data(value:Object):void {
	super.data = value;

	// Check to see if the data property is null.
	if (value== null) {
		return;
	} else {
		// data display and other stuff start here
	}
}

To create the background rectangle, you first have to start with a Graphic and then add the Rect and the parts of the Rect that you want to alter. You could just add the Rect and then alter the stroke and fill dynamically, but having them already defined makes it a little easier. I am only doing a Solid stroke and fill, if you wanted to do gradient or mix gradient and solid, then you definitely would want to do that dynamically. The Graphic is first, since it is on the bottom. Anything you want to display above the rectangle graphic goes afterward in the code.

<s:Graphic>
	<s:Rect id="columnRect">
		<s:stroke>
			<s:SolidColorStroke id="rectSolidColorStroke" />
		</s:stroke>
		<s:fill>
			<s:SolidColor id="rectSolidColor" />
		</s:fill>
	</s:Rect>
</s:Graphic>

Once you are ready to alter the column, you have to create the rectangle graphic for the background and you need to set the width and height to the super call for the column. If you don’t do this, then the rectangle is size 0 and you can’t see anything.

columnRect.width = super.width;
columnRect.height = super.height;

Since you are passing in the column data, you can modify the look of each column either by the xValue or the yValue. In this case, I wanted to change each column based on the yValue. I am only doing a simple solid fill and solid stroke, so I only need to change one color. I declared the colors to make it easier to set the uint values. Finally, I adjust the stroke weight and the fill alpha. These could also be changed based on the column data.

switch(value.xValue) {
	case 10:
		// Red Color
		columnFillColor = colorRed;
		columnStrokeColor = colorRed;
		break;
	case 20:
		// Blue Color
		columnFillColor = colorBlue;
		columnStrokeColor = colorBlue;
		break;
	case 30:
		// Green Color
		columnFillColor = colorGreen;
		columnStrokeColor = colorGreen;
		break;
	case 40:
		// Purple Color
		columnFillColor = colorPruple;
		columnStrokeColor = colorPruple;
		break;
}

rectSolidColorStroke.color = columnFillColor;
rectSolidColorStroke.weight = 2;
rectSolidColor.color = columnStrokeColor;
rectSolidColor.alpha = .3;

This example didn’t take very long to make and I will probably try to add some other feature to this simple chart.
View Source
[kml_flashembed publishmethod="dynamic" fversion="11.0.0" movie="http://deanlogic.com/demo/Flex/SimpleCharts/SimpleCharts.swf" width="800" height="500" targetclass="flashmovie" /]

Column Chart with Fill Function

When you have a column chart, sometimes you want to change the column colors based on the data. A question in the Flex Forum asked how to alter the column color on each column. To do this, yo need to use the fillFunction on a ColumnSeries to set the color of the fill. One issue with doing this, is how it affects the chart legend.

If you use the fills property or the fillFunction to define the fills of chart items, and you want a legend, you must manually create the Legend object for that chart.

But, this just gives me the opportunity to test out two different charting options.

I alter the stacked column chart that I created to answer another question on the forum. Since the column chart in this example is created dynamically, I had to add the fillFunction parameter when creating the column series for the green and red apple columns.

columnSeries1.fillFunction = greenAppleFillFunction;

Then I just created a simple function to change the color of the column if the count was less than 50.

private function greenAppleFillFunction(element:ChartItem, index:Number):IFill {
	var item:ColumnSeriesItem = ColumnSeriesItem(element);
	var count:Number = Number(item.yValue);

	if (count < 50) {
		return scFadeGreen;
	} else {
		return scGreen;,
	}
}

To make things easier, I had already defined my SolidColor values, this makes it easier to keep it consistent throughout the chart. In this example, I am only getting the yValue, but you could also get the xValue, if you wanted to change the column colors based on that.

Next I need to update the legend to reflect the new fillFunctions, which is fairly straight forward and I can also use the defined SolidColor parameters.

<mx:Legend  direction="horizontal" >
	<mx:LegendItem label="Red Apples" fill="{scRed}" />
	<mx:LegendItem label="Red under 50" fill="{scFadeRed}" />
	<mx:LegendItem label="Yellow Apples" fill="{scYellow}" />
	<mx:LegendItem label="Green Apples" fill="{scGreen}" />
	<mx:LegendItem label="Green under 50" fill="{scFadeGreen}" />
</mx:Legend>

I also added a Refresh Data button so that the data can be cycled and the column color changes can be seen.
View Source
[kml_flashembed publishmethod="dynamic" fversion="11.0.0" movie="http://deanlogic.com/demo/Flex/StackedColumnWithLineSeries/StackedColumnLineChart.swf" width="800" height="600" targetclass="flashmovie" /]

TextArea auto scroll update

There was a question on the Flex Forum about how to auto-scroll a TextArea. You can set the VerticalScrollPolicy to auto or you can add a little code to valueCommit to move the vertical scroller. Since I lost where I created the example of adding the code to the valueCommit, I decide to remake the example to show the difference. Both text areas are updated every 10 seconds with a random generated sentence, based off of quotes from Mark Twain.

The left TextArea box uses the VerticalScrollPolicy set to “auto”

<s:TextArea id="tmpTxtArea1" width="98%" height="98%" verticalScrollPolicy="auto" />

The right TextArea box uses the valueCommit code to move the verticalScrollBar

<s:TextArea id="tmpTxtArea2" width="98%" height="98%" 
   valueCommit="tmpTxtArea2.scroller.verticalScrollBar.value = tmpTxtArea2.scroller.verticalScrollBar.maximum"  />

View Source
[kml_flashembed publishmethod="dynamic" fversion="11.0.0" movie="http://deanlogic.com/demo/Flex/TextAreaScroll/TextAreaScroll.swf" width="800" height="300" targetclass="flashmovie" /]

While the right box doesn’t move the TextArea scroll bar 100%, it does move it.

The current issues I need to update with this example is a better random sentence generator and fix the regular expression that is supposed to remove the commas and periods before creating the word array. That’s probably some sort of project I can do later, so the sentences created are a little bit off, since I don’t remember how I did it in the previous example and the site I got the code idea from is no longer available.

Stacked Column Chart with Line Series

On the Flex Forum, I was attempting to help someone find their issue to a Stacked Column Chart with a Line Series. The y-axes values were not corresponding with the data being provided. This seemed like a glitch and I even attempted a work around by finding the minimum and maximum values. Finally, after looking at the Stacking Columns example and the Multiple Axis Example, reconstructed the chart using the static objects instead of dynamically creating the chart. From there, I recreated the chart items in a function and determined that the first issue the poster was having was building the column series incorrectly into a column set.

// add column series to column set
columnset.series = [columnSeries1, columnSeries2];

The second issues is that the created column set and the line series would be the two series added to the chart, not the individual column series.

myChart.verticalAxisRenderers = [verticalAxisRendererRight, verticalAxisRendererLeft];
// column set and linear series to Chart
myChart.series = [columnset, lineSeries];

I also added both x-axis and y-axis data column information, so that there would be no mistake as to were the data was coming from. These small changes apparently were the key to getting the axis values to match the column and charts.

var columnSeries1:ColumnSeries = new ColumnSeries();
columnSeries1.dataProvider = acChartData;
columnSeries1.xField = "hourOfDay";
columnSeries1.yField = "greenAppleCount";
columnSeries1.displayName = "Green";
columnSeries1.setStyle("fill", 0x009900);
columnSeries1.verticalAxis = verticalAxisLeft;

I used my apples data creator for this chart, since I already had that available on the other chart.
Another side note of obviousness, you fill columns and stroke lines.

View Source

[kml_flashembed publishmethod="dynamic" fversion="9.0.0" movie="http://deanlogic.com/demo/Flex/StackedColumnWithLineSeries/StackedColumnLineChart.swf" width="800" height="500" targetclass="flashmovie" /]

Find minimum or maximum value from Array

Browsing through the questions at the Adobe Flex forum again and came across one about having an issue with the Y-axis display on a dual-Y axis column/line chart. I’m not sure I gave the answer the poster was looking for, but my guess was that the minimum and maximum values for each LinearAxis was not set. You could set them to static values, but that wouldn’t be too useful. So, I did a quick search for some code to find the max value of an array and then modified it for AS3.

private function findMax(sourceArray:Array, sourceValue:String):Number {
	var maxNumber:Number = 0;
	for (var i:int = 0; i < sourceArray.length; i++) { 		var tmpNum:Number = new Number((sourceArray[i][sourceValue]).toString()); 		if(tmpNum > maxNumber) {
			maxNumber = sourceArray[i][sourceValue];
		}
	}

	return maxNumber;
}

private function findMin(sourceArray:Array, sourceValue:String, startMax:Number):Number {
	var minNumber:Number = startMax;
	for (var i:int = 0; i < sourceArray.length; i++) {
		var tmpNum:Number = new Number((sourceArray[i][sourceValue]).toString());
		if(tmpNum < minNumber) {
			minNumber = sourceArray[i][sourceValue];
		}
	}

	return minNumber;
}

— update —
There is apparently even an easier way of finding the minimum and maximum in an array of values using a Math function. However, you still have to split out the particular set of values from the overall array, which I don’t think there is a way to do.

Math.max(Array[]);
Math.min(Array[]));

It is pretty straight forward. Go through the array and find the value for a particular column, then check to see if it is smaller or larger than the previous stored value. The only difference between the two, is setting the starting high value for finding the minimum. So, when using these functions, you should find the maximum first and use that value as the startMax in order to find the minimum. This is who it was used in the LinearAxis code.

// VERTICAL AXIS
var verticalAxisLeft:LinearAxis = new LinearAxis();
verticalAxisLeft.autoAdjust = true;
verticalAxisLeft.maximum = Math.ceil(findMax(SMITH.source, "open"));
verticalAxisLeft.minimum = Math.ceil(findMin(SMITH.source, "open", verticalAxisLeft.maximum));

var verticalAxisRight:LinearAxis = new LinearAxis();
verticalAxisRight.autoAdjust = true;
verticalAxisRight.maximum = Math.ceil(findMax(DECKER.source, "close"));
verticalAxisRight.minimum =  Math.ceil(findMin(DECKER.source, "close", verticalAxisRight.maximum));

However, using the right Array, that has higher values than the left, will cause some issues. It is probably best to either use 0 or the smaller minimum value of the two arrays.

Spark LineGrid Component

Since I had a day off, I decided to work on converting my old Flex Examples to the new Flex 4.  As stated in a previous post, the new Flex 4 breaks Degrafa and Degrafa seems to be defunct now.  Most of the drawing functions are handled with spark and sprite functions, but little things like arcs and line repeaters are not.  So where before it was easy enough to create a repeating line in Degrafa, now I have to do a loop to create the lines needed.  Well, in this case, instead of drawing lines, I’m drawing rectangles.  While it might seem simple at first just to draw a bunch of rectangles together to create a grid, there is a little trickiness to it.  You can have to account for the size of the total grid, based on the number of columns, rows and the grid box size.  And you also have to use both the column and row count value to draw the correct number of rows and columns and at the right size.  It is all just a matter of thinking about it for a few moments and then having an “ah ha!” moment.  Another little quirk with the components is that when you add a visual element, it puts it in the center of the group component.  On the Egg Timer, I just left it there for now because it worked for what I needed.  I might change it later.  But for the LineGrid, it made for it not to line up correctly.  So, before I start drawing the rectangles, I had to determine the actual 0,0 location first.  It also took a couple tries to make sure I was using the right zero.


// Find the actual 0,0 start
var actualZeroX:int = -1 * ((columnCount * boxSize) * .5);
var actualZeroY:int = -1 * ((rowCount * boxSize) * .5);

One good thing about the new components, is that when you use the declarations, it is the same as creating a set function, which means less code.  I simply added declarations for the column and row counts, then put those values where I need them.  When I use the LineGrid component I add the values I need just like any other attribute.


<components:LineGrid id="lineGrid1" rowCount="5" columnCount="5" boxSize="50" lineThickness="4" lineColor="0x009900" />

Here is the example showing a grid with equal columns and rows and then two other grids with column or rows determined by the size of the application.

[kml_flashembed publishmethod="dynamic" fversion="10.0.0" movie="http://demo.deanlogic.com/Flex/GridLineRepeater/SparkGridLines.swf" width="800" height="300" targetclass="flashmovie"]

Get Adobe Flash player

Autoscroll Textarea

One of the ways I like to debug my Flex applications is putting a TextArea item that is visible when needed to display certain items that usually would be display in a trace.  The benefit of this little trick is that I can see what is going on without having to go through Flex Builder.  Also, I happened to create a web service debugging application and it displayed the error and result text from the web service.  When displaying either debug or general result information, it is helpful if the TextArea scrolls up to show the latest information added.  I found code on the to do this in Flex 3, but things changed in Flex 4.  So I did a little searching and found some code that had a little too much code.  There is a warning at the bottom of that post which states the API at the time was in Beta.  Maybe adding event listeners is the more correct way to automatically scroll the TextArea, but it certainty isn’t the quickest way.  Since the Flex 3 version was fairly simple, I took what I saw there and applied it in the way the old method worked.

The first thing is that the scroller is now it is own component within the TextArea.  So, you first have to access that withing the TextArea.  Then you need to choose either the vertical or horizontal scrollbar.  Since I set the width and the words automatically wrap, I only need the vertical scrollbar.  Then you get the value of the scrollbar, which you can read or set.  The key is to set the scrollbar to its maximum position, which in the case of a vertical scoller would show the bottom of the TextArea.  You change this value with the valueCommit function, that allows you to change things after a value is added.  Just don’t change the content value or you go into a loop.


<s:TextArea id="fooText" width="200" height="200"
valueCommit="fooText.scroller.verticalScrollBar.value = fooText.scroller.verticalScrollBar.maximum" />

Unfortunately, it doesn’t seem to scroll completely down to the bottom completely.  I’ve created a little application to show text being added to the TextArea.  Every 10 seconds a random set of words will be added to each of the TextAreas.  As the amount of text increases, the TextArea with the dynamic scroller will scroll down, while the other TextArea just increases the scroller size.  To generate the random words, I used a few quotes from the Mark Twain quote site.  From those quotes, I used a script to convert the phrase words into an array. I modified the examples in order to pass in the array that I want to add the words to and get back a new array of words.  From there I used a basic random number in range script to get a random number of words.  Once I had the random number of words, I just grabbed that many words in a loop from the Array.  Finally, I adjusted the first word to make sure it had the first letter as upperCase and the rest of the words to lowerCase.


public static function getArrayFromString(inputPhrase:String, sourceArray:Array):Array {
var reg:RegExp = /\W/i;
var wordsAsArray:Array = inputPhrase.replace(reg, "").split(" ");

for(var w:int=0; w < wordsAsArray.length; w++){
sourceArray.push(wordsAsArray[w].toString());
}

return sourceArray;
}

public static function upperCase(str:String) : String {
var firstChar:String = str.substr(0, 1);
var restOfString:String = str.substr(1, str.length);

return firstChar.toUpperCase() + restOfString.toLowerCase();
}

Here is the example. When the text expands past the available area for the first time, bot TextAreas look the same.  When the next random phrase is created, then the difference is more apparent.

Get Adobe Flash player