Created
August 23, 2011 22:02
-
-
Save seancoyne/1166719 to your computer and use it in GitHub Desktop.
Scale Flex label text to fit available width
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
| import flash.text.AntiAliasType; | |
| import flash.text.Font; | |
| import flash.text.GridFitType; | |
| import flash.text.TextLineMetrics; | |
| import mx.controls.Label; | |
| import mx.core.Application; | |
| import mx.core.UITextFormat; | |
| import mx.styles.CSSStyleDeclaration; | |
| import mx.styles.StyleManager; | |
| public class LabelUtil { | |
| public function LabelUtil() {} | |
| static public function constrainTextToWidth(label:Label, htmlText:String):void { | |
| var style:CSSStyleDeclaration = StyleManager.getStyleDeclaration("." + label.styleName); | |
| var fontSize:Number = style.getStyle("fontSize") as Number; | |
| label.setStyle("fontSize", fontSize); | |
| label.htmlText = htmlText; | |
| label.invalidateSize(); | |
| label.validateNow(); | |
| while (getTextWidth(label.text, fontSize, style) > label.width) { | |
| fontSize = fontSize - 0.5; | |
| label.setStyle( "fontSize", fontSize ); | |
| } | |
| } | |
| static public function getTextWidth(text:String,fontSize:Number,style:CSSStyleDeclaration):Number { | |
| var textFormat:UITextFormat = new UITextFormat( | |
| Application.application.systemManager, | |
| style.getStyle("fontFamily"), | |
| fontSize, | |
| null, | |
| style.getStyle("fontWeight") == "bold", | |
| style.getStyle("fontStyle") == "italic", | |
| null, | |
| null, | |
| null, | |
| null, | |
| style.getStyle("paddingLeft"), | |
| style.getStyle("paddingRight"), | |
| style.getStyle("textIndent") | |
| ); | |
| textFormat.antiAliasType = flash.text.AntiAliasType.ADVANCED; | |
| textFormat.gridFitType = flash.text.GridFitType.PIXEL; | |
| var textMetrics : TextLineMetrics = textFormat.measureText(text); | |
| return textMetrics.width; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Grabbed from http://blog.grio.com/2009/10/wrangling-flex-labels-autosizing-text.html