Return to Snippet

Revision: 39795
at January 21, 2011 02:52 by mgeduld


Initial Code
import flash.text.TextField;

var t : TextField = new TextField();
t.text = "Now is the time for all good men to come to the aid of their party."
t.width = 100;
t.height = 40;
t.border = true;
//t.multiline = true;
//t.wordWrap = true;
truncate( t );
addChild( t );

function truncate( textField : TextField, addElipsis : Boolean = true, ellipsis : String = "\u2026" ) : void
{
	var tempTextField : TextField;
	if ( ! textOverflowing( textField ) ) return;
	tempTextField = copyTextField( textField );
	while( textOverflowing( tempTextField, ellipsis ) )
		tempTextField.text = tempTextField.text.substr( 0, tempTextField.text.length - 1 );
	tempTextField.appendText( ellipsis );
	textField.text = tempTextField.text;
}

function textOverflowing( textField : TextField, suffix : String = null ) : Boolean
{
	var margin : Number = 4; //Flash adds this to all textfields;
	var tempTextField : TextField = copyTextField( textField );
	if ( suffix ) tempTextField.appendText( suffix );
	
	if ( tempTextField.textWidth > tempTextField.width - margin 
		|| tempTextField.textHeight > tempTextField.height - margin ) return true;
	return false;
}

function copyTextField( original : TextField ) : TextField
{
	var copy : TextField = new TextField();
	copy.width = original.width;
	copy.height = original.height;
	copy.multiline = original.multiline;
	copy.wordWrap = original.wordWrap;
	copy.embedFonts = original.embedFonts;
	copy.antiAliasType = original.antiAliasType;
	copy.autoSize = original.autoSize;
	copy.defaultTextFormat = original.getTextFormat();
	copy.text = original.text;
	return copy;
}

Initial URL
http://www.marcusgeduld.com

Initial Description


Initial Title
Truncate overflow text in a textfield and add an ellipsis (...)

Initial Tags
text

Initial Language
ActionScript 3