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


/ Published in: ActionScript 3
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import flash.text.TextField;
  2.  
  3. var t : TextField = new TextField();
  4. t.text = "Now is the time for all good men to come to the aid of their party."
  5. t.width = 100;
  6. t.height = 40;
  7. t.border = true;
  8. //t.multiline = true;
  9. //t.wordWrap = true;
  10. truncate( t );
  11. addChild( t );
  12.  
  13. function truncate( textField : TextField, addElipsis : Boolean = true, ellipsis : String = "\u2026" ) : void
  14. {
  15. var tempTextField : TextField;
  16. if ( ! textOverflowing( textField ) ) return;
  17. tempTextField = copyTextField( textField );
  18. while( textOverflowing( tempTextField, ellipsis ) )
  19. tempTextField.text = tempTextField.text.substr( 0, tempTextField.text.length - 1 );
  20. tempTextField.appendText( ellipsis );
  21. textField.text = tempTextField.text;
  22. }
  23.  
  24. function textOverflowing( textField : TextField, suffix : String = null ) : Boolean
  25. {
  26. var margin : Number = 4; //Flash adds this to all textfields;
  27. var tempTextField : TextField = copyTextField( textField );
  28. if ( suffix ) tempTextField.appendText( suffix );
  29.  
  30. if ( tempTextField.textWidth > tempTextField.width - margin
  31. || tempTextField.textHeight > tempTextField.height - margin ) return true;
  32. return false;
  33. }
  34.  
  35. function copyTextField( original : TextField ) : TextField
  36. {
  37. var copy : TextField = new TextField();
  38. copy.width = original.width;
  39. copy.height = original.height;
  40. copy.multiline = original.multiline;
  41. copy.wordWrap = original.wordWrap;
  42. copy.embedFonts = original.embedFonts;
  43. copy.antiAliasType = original.antiAliasType;
  44. copy.autoSize = original.autoSize;
  45. copy.defaultTextFormat = original.getTextFormat();
  46. copy.text = original.text;
  47. return copy;
  48. }

URL: http://www.marcusgeduld.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.