AS3 - trim text for specific width and heigh


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

Hi;

Sometimes you need to "trim" textifield for specific height... This solves just this, perfect for news, news-readers, rss etc


Copy this code and paste it in your HTML
  1. package com.streameye.utils {
  2.  
  3. import flash.text.TextField;
  4.  
  5. public class TrimTextUtil {
  6.  
  7. public function TrimTextUtil() {
  8.  
  9. }
  10.  
  11. public static function trimTfForHeight(_tf:TextField, _height:Number = 0 ):void{
  12.  
  13. _tf.multiline = true;
  14. _tf.wordWrap = true;
  15. _tf.condenseWhite = true;
  16.  
  17. var heightNeeded:Number = _height != 0 ? _height : _tf.height;
  18.  
  19. if(_tf.textHeight > heightNeeded){
  20.  
  21. var safeLinesNum:int = 0;
  22. var preciseFixer:int = 0;
  23. var safeTrim:Number = 0;
  24.  
  25. for(var i:Number = 0; i< _tf.numLines-1; i++){
  26. if(_tf.getLineMetrics(i).height*i + _tf.getLineMetrics(i).ascent < heightNeeded - preciseFixer){
  27. safeTrim += _tf.getLineLength(i);
  28. safeLinesNum++;
  29. }
  30. }
  31.  
  32. var suffix:String = " ...";
  33. _tf.text = truncate(_tf.text, safeTrim, suffix);
  34. }
  35.  
  36. }
  37.  
  38. public static function truncate(p_string:String, p_len:uint, p_suffix:String = "..."):String {
  39. if (p_string == null) {
  40. return '';
  41. }
  42. p_len -= p_suffix.length;
  43. var trunc:String = p_string;
  44. if (trunc.length > p_len) {
  45. trunc = trunc.substr(0,p_len);
  46. if (/[^\s]/.test(p_string.charAt(p_len))) {
  47. trunc = (trunc.replace(/\w+$|\s+$/,'')).replace(/\s+$/, '');
  48. }
  49. trunc += p_suffix;
  50. }
  51. return trunc;
  52. }
  53.  
  54. public static function stripTags(s_text:String):String{
  55. return s_text.replace(/<.*?>/g, "")
  56. }
  57.  
  58. //// ARRAYS
  59.  
  60. public static function chunks(array:Array, chunk_size:uint):Array {
  61. var chunks:Array = new Array();
  62. for (var i:int = 0; i < (array.length / chunk_size); i++) {
  63. chunks.push(array.slice(i * chunk_size, (i + 1) * chunk_size));
  64. }
  65. return chunks;
  66. }
  67.  
  68. }//end
  69. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.