Return to Snippet

Revision: 55114
at January 26, 2012 22:13 by burnandbass


Initial Code
package com.streameye.utils {
	
	import flash.text.TextField;

	public class TrimTextUtil {
		
		public function TrimTextUtil() {
			
		}
		
		public static function trimTfForHeight(_tf:TextField, _height:Number = 0 ):void{
			
			_tf.multiline = true;
			_tf.wordWrap = true;
			_tf.condenseWhite = true;
			
			var heightNeeded:Number = _height != 0 ? _height : _tf.height;
			
			if(_tf.textHeight > heightNeeded){			
				
				var safeLinesNum:int = 0;
				var preciseFixer:int = 0;
				var safeTrim:Number = 0;
								
				for(var i:Number = 0; i< _tf.numLines-1; i++){
					if(_tf.getLineMetrics(i).height*i + _tf.getLineMetrics(i).ascent < heightNeeded - preciseFixer){
						safeTrim += _tf.getLineLength(i);
						safeLinesNum++;
					}
				}
				
				var suffix:String = " ...";
				_tf.text = truncate(_tf.text, safeTrim, suffix);
			}
			
		}
		
		public static function truncate(p_string:String, p_len:uint, p_suffix:String = "..."):String {
			if (p_string == null) {
				return '';
			}
			p_len -=  p_suffix.length;
			var trunc:String = p_string;
			if (trunc.length > p_len) {
				trunc = trunc.substr(0,p_len);
				if (/[^\s]/.test(p_string.charAt(p_len))) {
					trunc = (trunc.replace(/\w+$|\s+$/,'')).replace(/\s+$/, '');
				}
				trunc +=  p_suffix;
			}
			return trunc;			
		}
		
		public static function stripTags(s_text:String):String{
			return s_text.replace(/<.*?>/g, "")
		}
		
		////  ARRAYS
		
		public static function chunks(array:Array, chunk_size:uint):Array {
			var chunks:Array = new Array();
			for (var i:int = 0; i < (array.length / chunk_size); i++) {
				chunks.push(array.slice(i * chunk_size, (i + 1) * chunk_size));
			}
			return chunks;
		}
		
	}//end
}

Initial URL


Initial Description
Hi;

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

Initial Title
AS3 - trim text for specific width and heigh

Initial Tags
text

Initial Language
ActionScript 3