First I have to say sorry to all the not ‘actionscript-geeks’, but I have another script I want to share. I made a TextField behaviour that might come in handy for other people too.. I made a short video to show how it works.
It is called AutomaticFontSizeBehaviour :)
package utils {
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.events.TextEvent;
/**
* @author Jankees.van.Woezik
*/
public class AutomaticFontSizeBehaviour {
private var _textField:TextField;
private var _startSize:Number;
private var _currentSize:Number;
private var _prevText:String;
private var _maxHeight:Number;
private var _minimalFontSize:uint;
public function AutomaticFontSizeBehaviour(textField:TextField,inStartSize:Number,inMinimalFontSize:uint = 32) {
_minimalFontSize = inMinimalFontSize;
_startSize = inStartSize;
_currentSize = inStartSize;
_textField = textField;
_prevText = "";
_maxHeight = _textField.height;
_textField.addEventListener(KeyboardEvent.KEY_UP,update);
_textField.addEventListener(Event.CHANGE,update);
_textField.addEventListener(TextEvent.TEXT_INPUT,update);
_textField.addEventListener(Event.REMOVED_FROM_STAGE,dispose);
setFontSize(_startSize);
update();
}
public function update(event:Event = null):void {
_textField.scrollV = 0;
setFontSize(_startSize);
while (_maxHeight < _textField.textHeight + (4 * _textField.numLines)) {
if(_currentSize <= _minimalFontSize) break;
setFontSize(_currentSize - 0.5);
}
if(_currentSize <= _minimalFontSize) {
_textField.text = _prevText;
} else {
_prevText = _textField.text;
}
}
private function setFontSize(inSize:Number):void {
_currentSize = inSize;
var currentTextFormat:TextFormat = _textField.getTextFormat();
currentTextFormat.size = _currentSize;
_textField.setTextFormat(currentTextFormat);
_textField.defaultTextFormat = currentTextFormat;
}
/**
* Dispose everything
*/
private function dispose(event:Event):void {
_textField.removeEventListener(KeyboardEvent.KEY_UP,update);
_textField.removeEventListener(Event.CHANGE,update);
_textField.removeEventListener(TextEvent.TEXT_INPUT,update);
_textField.removeEventListener(Event.REMOVED_FROM_STAGE,dispose);
_textField = null;
}
}
}
update: Thanks to Thijs for the update! Copy & paste is now supported!
Like this post? Follow me at @jankeesvw on Twitter