Last active
September 20, 2016 19:07
-
-
Save MindScriptAct/438a18fa41e5f8a5afeebd50a14107df to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by Raimundas Banevicius on 8/15/2016. | |
*/ | |
package utils.text { | |
import flash.text.TextField; | |
import flash.text.TextFieldAutoSize; | |
import flash.text.TextFormat; | |
public class TextHelper { | |
/** | |
* Will fill 1-line text field with text, if it does not fit - will reduce text size until it fits. | |
* @param textField textField to fill | |
* @param text text for textField. | |
* @param defaultSize initial size for text. To restore font size if it was reduced before. | |
*/ | |
public static function fitTextToField(textField:TextField, text:String, defaultSize:int = -1):void { | |
var textFormat:TextFormat = textField.getTextFormat(); | |
if (defaultSize > 0) { | |
textFormat.size = defaultSize; | |
} | |
var testField:TextField = new TextField(); | |
testField.autoSize = TextFieldAutoSize.LEFT; | |
testField.multiline = false; | |
testField.text = text; | |
testField.setTextFormat(textFormat); | |
while (testField.width > textField.width && textFormat.size > 1) { | |
textFormat.size = Number(textFormat.size) - 1; | |
testField.text = text; | |
testField.setTextFormat(textFormat); | |
} | |
textField.text = text; | |
textField.setTextFormat(textFormat); | |
} | |
/** | |
* Will fill 1-line text field with text, if it does not fit - will cut it and add '...' | |
* @param textField textField to fill | |
* @param text text for textField. | |
* @param postText will be added to end of text if it does not fit. | |
*/ | |
public static function cutTextInField(textField:TextField, text:String, postText:String = "..."):void { | |
var textFormat:TextFormat = textField.getTextFormat(); | |
var testField:TextField = new TextField(); | |
testField.autoSize = TextFieldAutoSize.LEFT; | |
testField.multiline = false; | |
testField.text = text; | |
testField.setTextFormat(textFormat); | |
if (testField.width > textField.width) { | |
var cutText:String = text; | |
while (testField.width > textField.width && cutText.length > 0) { | |
cutText = cutText.substr(0, cutText.length -1); | |
testField.text = cutText + postText; | |
testField.setTextFormat(textFormat); | |
} | |
textField.text = cutText + postText; | |
} else { | |
textField.text = text; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment