How to use Text Layout Framework in Flex 3.2 or AIR 1.5

The goal of this article is to explain what the Text Layout Framework is and how you can use it to display rich text inside of Flash Player 10. While I will not cover all the possibilities of this framework, I hope I will give you enough of a push to get up to cruising speed.

As usual, you can find a demo and the source code for the examples in this article packaged as a Flex 3.2 project ZIP file. So if you prefer to see the code before reading the theory, then see the section “Code time: An example using the Text Layout Framweork in Flex 3.2”.

Note: For a Bulgarian translation you can check this website.

What is the Text Layout Framework

The Flash Text Engine (FTE) available in Flash Player 10 and Adobe AIR 1.5 brings support for many new text capabilities. There is an API that provides low-level access to this engine, but if you want to use the API you have to write a lot of code. Thus, the FTE is intended to provide the foundation for libraries that leverage these capabilities and make life easier for the developer.

And this is exactly what the Text Layout Framework is. It is a library written in pure ActionScript, and thus can be used in Flash CS4, Flex 3.2 or Gumbo, or AIR 1.5.

The Text Layout Framework provides support for:

  • Bidirectional text, vertical text and over 30 writing systems including Arabic, Hebrew, Chinese, Japanese, Korean, Thai, Lao, the major writing systems of India, and others.
  • Selection, editing and flowing text across multiple columns and linked containers, as well as around inline images
  • Vertical text, Tate-Chu-Yoko (horizontal within vertical text) and justifier for East Asian typography
  • Rich typographical controls, including kerning, ligatures, typographic case, digit case, digit width and discretionary hyphens
  • Cut, copy, paste, undo and standard keyboard and mouse gestures for editing
  • Rich developer APIs to manipulate text content, layout, markup and create custom text components.

Below are some screen shots from the samples you can find on

Japanese text, left to right, vertical, you can see the text selection Text flowing in linked containers

Text formatting:  orientation, alignment, rotation, spacesSetting the number of columns

Inline imagesText blends and effects

Understanding Text Layout Framework components

The Text Layout Framework (TLF) comprises three components and ten packages. All the packages are subpackages of the flashx.textlayout package. As I said this framework is implemented using pure ActionScript 3, and thus can be used in Flash CS4, Flex 3.2, Gumbo (the Text Layout Framework is part of Gumbo), or AIR 1.5. And of course you have to target Flash Player 10. Here is a short description of the three components in TLF:

  1. textLayout_core.swc is the main component and handles data storage, flowing text into containers, and rendering the containers
  2. textLayout_conversion.swc is used to import text into the framework, and to export it
  3. textLayout_edit.swc facilitates text selection and text editing

One way to look at the TLF, is by comparing it with the MVC pattern. If you apply this pattern, then you will have:

  1. The model is defined mainly by the flashx.textlayout.elements package, which includes classes/interfaces that define the data structure that holds the text. Another package, flashx.textlayout.formats, is used for storing the format information. The package flashx.textlayout.conversion can be considered part of the model as it embodies the rules for importing/exporting the data
  2. The view includes three packages that handle the rendering of text for display. You can choose to display the text using one of the two different methods: using  flashx.textlayout.factory package you can display static text, and using flashx.textlayout.container you can display containers for dynamic text. The flashx.textlayout.compose package defines the methods for positioning and displaying dynamic text in containers
  3. The controller is represented by two packages that define how the user can interact with the text (selecting, editing, copy/paste, undo, and so on): flashx.textlayout.edit and flashx.textlayout.operations

The Model and Text Flow hierarchy

The model uses a hierarchical tree to represent text. Each element of the tree is a class from the package flashx.textlayout.elements. The root element is always an instance of the TextFlow class, and conceptually represents an entire story of text (the term story comes from DTP, and means a collection of text that should be treated as one unit). For example, the article you are reading now could be a story.

The rest of the elements are:

  • div – a division of text, can contains only div or p elements
  • p – a paragraph, can contain any element but div
  • a – a link; can contain tcy, span, img, tab, br
  • tcy – a run of horizontal text, used in vertical text; for example in Japanese you can have this type of element; can contain a, span, img, tab, br
  • span – a run of text in a paragraph; can contain only text
  • img – an image in a paragraph
  • tab – a tab character
  • br – a break character. Text will continue on the next line, but it doesn’t start a new paragraph

The TextFlow can have only these two elements as children: div and p. Here is how the model can look for a story:

TLF hierarchy

This Text Flow hierarchy translates to an XML document, using TLF Markup. Basically the nodes can be: TextFlow, div, p, a, img, span, tcy, br, and tab. At the same time, each node has an ActionScript class implementation: TextFlow, DivElement, ParagraphElement, LinkElement, TCYElement, SpanElement, InlineGraphicElement, TabElement, and BreakElement. All these classes inherit directly or indirectly from the class FlowElement.

Now, let’s see how you can create a TextFlow element. Basically, there are two ways you can create a TextFlow element: by using an XML object, or by creating the nodes and assembling them together in a tree (similar to creating an XML using DOM).

Creating a TextFlow element using an XML:

   1: private static const textInput:XML = <TextFlow xmlns="">
   2: <div>
   3:     <p>
   4:         <img source="air.png"/>
   5:         <span>Flex is a highly productive, free open source framework for building and maintaining expressive web applications...</span>
   6:         <br/>
   7:     </p>
   8: </TextFlow>;
  10: private var textFlow:TextFlow = TextFilter.importToFlow(textInput, TextFilter.TEXT_LAYOUT_FORMAT);

As you can see TextFilter class is used for importing the XML and creates an instance of TextFlow. The second parameter of the import method tells what format the XML is written in. In this case I am using TLF Markup.

Creating a TextFlow using the FlowElement classes:

   1: var textFlow:TextFlow = new TextFlow();
   2: var p:ParagraphElement = new ParagraphElement();
   3: var span:SpanElement = new SpanElement();
   4: span.text = "Hello, World!";
   5: p.addChild(span);
   6: textFlow.addChild(p);

The Model and formatting information

As noted earlier, the model stores the formatting information too. If you choose to create the TextFlow element using XML, then you can add the properties like attributes on the node you want:

   1: var text:XML = <TextFlow xmlns="" fontSize="14" textIndent="15" marginBottom="15" paddingTop="4" paddingLeft="4">"
   2:        <p>
   3:         <span>There are many </span>
   4:         <span fontStyle="italic">such</span>
   5:     </p>
   6: </TextFlow>;

Or, if you create it out of FlowElement classes, you can do it like this:

   1: var cf:CharacterFormat = new CharacterFormat();
   2: cf.fontSize = 14;
   3: textFlow.characterFormat = cf;

All the properties that can be set for all the nodes are grouped into three types: container, paragraph, and character properties. You can see the API for the flashx.textlayout.formats package here.

Container formats apply on the entire container of text, for example column properties and padding values. Container formats can be applied only on a TextFlow, DivElement, or other class that implements IContainerController. You can apply these properties using an instance of the ContainerFormat class.

Paragraph formats apply to an entire paragraph of text: justification, margins, tab stops. They can be applied on TextFlow, DivElement, and ParagraphElement. You apply these formats using an instance of ParagraphFormat class.

Character formats apply only to a single character or run of characters: font size, color, tracking, kerning, superscript. You can assign them to any FlowElement, thus you can set the font size for an entire story by setting the property on the TextFlow, or the SpanElement. You use a CharacterFormat class to apply the properties.

When you apply a format on a FlowElement, you have two options: to overwrite the existing formats, or to keep the existing ones, and add the new format. Below is code illustrating both options. To keep the existing format, when you create the new format you pass an instance of that format to the constructor.

   1: //overwrite the characterFormat for the TextFlow
   2: var cf:CharacterFormat = new CharacterFormat();
   3: cf.fontSize = 14;
   4: textFlow.characterFormat = cf;
   6: //keeps the existent characterFormat, and change only the font size
   7: var cf:CharacterFormat = new CharacterFormat(textFlow.characterFormat);
   8: cf.fontSize = 14;
   9: textFlow.characterFormat = cf;

Finally, if you apply a font-size change to the TextFlow element, then this change will be applied to all its children that don’t have a font-size explicitly set on them.

Important: every time you apply changes to a TextFlow object that has been displayed, you have to call the method updateAllContainers() on the flowComposer property of the TextFlow object to trigger the update of the display:

   1: textFlow.flowComposer.updateAllContainers();

The View: displaying the text

You’ve learned how to create the model for storing the text using the TextFlow class. Now it is time to see how you can display this text. Basically, you have two options depending on what level of control you need to have on the text. Both methods convert the TextFlow into TextLine instances, which are part of the new Flash Text Engine. In order to display the TextLine you have to add it to a control that is a subclass of DisplayObjectContainer, such as Sprite.


If you just want to display the text and you don’t want to interact with it (for example, by selecting parts of it), then you can use TextLineFactory. This class has two static methods, createTextLineFromTextFlow and createTextLinesFromString, which create TextLine objects out of a TextFlow or a string. Here is an example of how to use it:

   1: var sprite:Sprite = new Sprite();
   2: //this serves as the bound for the text
   3: var bounds:Rectangle = new Rectangle(0,0,300,100);
   4: var txtStr:String = "This is sample text showing lines created by TextLineFactory.";
   5: var characterFormat:CharacterFormat = new CharacterFormat();
   6: characterFormat.fontSize = 48;
   8: TextLineFactory.createTextLinesFromString(callback, txtStr, bounds, characterFormat);
  10: //this is the callback function that will be called by createTextLinesFromString() 
  11: //method for each TextLine
  12: function callback(tl:TextLine):void{
  13:     sprite.addChild(tl);
  14: }

Flow Composer

If you want to be able to select or edit, then you have to use the Flow Composer. Every TextFlow instance has an object that implements the IFlowComposer interface. You can use the property flowComposer of the TextFlow to access this object. This object has the methods to associate the text with one or more containers and prepare the text for display.

For the container you can use any instance of a DisplayObjectContainer, such as Sprite for example. In order to link a container to another one (when you do this, if the text overflows the first container, then it will flow into the second container) to support scrolling or container formatting, the DisplayObjectContainer is wrapped inside an instance of DisplayObjectContainerController.

This is how you can add the container to a TextFlow object, and then trigger the formatting and displaying of the text:

   1: var sprite:Sprite = new Sprite();
   2: canvas.rawChildren.addChild(sprite);
   3: var controller:IContainerController = new DisplayObjectContainerController(sprite, 600, 400);
   4: textFlow.flowComposer.addController(controller);
   5: textFlow.flowComposer.updateAllContainers();

Adding interaction capabilities to the TextFlow

If you want to make the text selectable, you have to use a manager, SelectionManager and associate it with the interactionManager property of the TextFlow. You setup the manager like this:

   1: textFlow.interactionManager = new SelectionManager();

After the manager is assigned to the TextFlow’s interactionManager, the TextFlow has access to the event handlers of the manager. For example, it knows when a key is pressed, when the container loses or gains focus, and when text is selected.

If you want to enable editing features on top of selecting features, then you would use EditManager instead of SelectionManager:

   1: textFlow.interactionManager = new EditManager();

And finally, if you want to enable Undo/Redo commands, you use UndoManager, like this:

   1: textFlow.interactionManager = new EditManager(new UndoManager());

Import and Export text

For import/export you use the TextFilter object from the flashx.textlayout.conversion package. You’ve already seen one way to import XML to the TextFlow. What you have to do is this:

   1: var textInput:XML = <TextFlow><div><span>Some text here.</span></div></TextFlow>;
   2: var textFlow:TextFlow = TextFilter.importToFlow(textInput, TextFilter.TEXT_LAYOUT_FORMAT);

You can also import plain text (you set the convertor to parse string, by setting the second argument to TextFilter.PLAIN_TEXT_FORMAT):

   1: var textInput:String = "Hello World, this is plain text";
   2: var textFlow:TextFlow = TextFilter.importToFlow(textInput, TextFilter.PLAIN_TEXT_FORMAT);

Text Layout Framework can export text in any one of three formats: plain text, FXG, or Text Layout Format. For example this is how you export XML text from an existing TextFlow instance using Text Layout Format:

   1: var out:XML = TextFilter.export(textFlow, TextFilter.TEXT_LAYOUT_FORMAT, ConversionType.XML_TYPE );

Code time: an example of using the Text Layout Framework in Flex 3.2

If you want to run the example, click here; you can download the project from here. This example uses flowComposer. I use a single container, and the textFlow is created using an XML file. In this XML I have four paragraphs in four languages, two of them are rleft-to-right, and two are right-to-left.

Also I add some controls to change the font size, to change the number of columns, and to change the direction of text for the first two paragraphs.

Screen shot of the app

You can click on the text, scroll, edit, delete, insert, undo, copy/paste and so on.

Without further delay, here is the source code (don’t forget that you need the Flex SDK 3.2, and the three SWC libraries of the Framework; if you choose to download the project, then you’ll have these libraries):

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <mx:Application xmlns:mx="" xmlns:local="*" layout="absolute" creationComplete="init()" horizontalScrollPolicy="off" viewSourceURL="srcview/index.html">
   3: <mx:Script>
   4:     <![CDATA[
   5:         import mx.controls.CheckBox;
   6:         import mx.collections.ArrayCollection;
   7:         import flashx.textLayout.formats.Direction;
   8:         import flashx.textLayout.elements.InlineGraphicElement;
   9:         import;
  10:         import flashx.textLayout.formats.ContainerFormat;
  11:         import flashx.textLayout.formats.ICharacterFormat;
  12:         import flashx.textLayout.formats.CharacterFormat;
  13:         import;
  14:         import flashx.textLayout.edit.UndoManager;
  15:         import flashx.textLayout.edit.EditManager;
  16:         import flashx.textLayout.container.DisplayObjectContainerController;
  17:         import flashx.textLayout.conversion.TextFilter;
  18:         import flashx.textLayout.elements.TextFlow;
  21:         public var directions:ArrayCollection = new ArrayCollection(
  22:                             [
  23:                                 {label:"Left-to-Right", data:Direction.LTR},
  24:                                 {label:"Right-to-Left", data:Direction.RTL}
  25:                             ]
  26:                         );
  28:         [Embed(source="air.png")]
  29:         [Bindable]
  30:         static public var imgClass:Class;
  32:         private var _textContainer:Sprite = null;
  34:         private static const textInput:XML = <TextFlow xmlns="">
  35: <div>
  36:  <span>And the text come here...</span>
  37: </div>
  38: </TextFlow>;
  40:         private var _textFlow:TextFlow;
  42:         private function init():void {
  43:             _textContainer = new Sprite();
  44:             canvas.rawChildren.addChild(_textContainer);
  46:             _textFlow = TextFilter.importToFlow(textInput, TextFilter.TEXT_LAYOUT_FORMAT);
  47:             _textFlow.flowComposer.addController(new DisplayObjectContainerController(_textContainer, canvas.width-40, canvas.height));
  48:             _textFlow.addEventListener(StatusChangeEvent.INLINE_GRAPHIC_STATUS_CHANGED, picLoaded);
  49:             //adding Select/Edit/Copy/Paste/Undo features
  50:             _textFlow.interactionManager = new EditManager(new UndoManager());
  51:             // initialize with a selection before the first character
  52:             _textFlow.interactionManager.setSelection(0,0);
  54:             _textFlow.flowComposer.updateAllContainers();
  55:         }
  57:         private function picLoaded(event:StatusChangeEvent):void {
  58:             var image:InlineGraphicElement = event.element as InlineGraphicElement;
  59:             _textFlow.flowComposer.updateAllContainers();
  60:         }
  62:         private function changeFontSize(event:SliderEvent):void {
  63:             var cf:CharacterFormat = new CharacterFormat(_textFlow.characterFormat);
  64:             cf.fontSize = event.value;
  65:             _textFlow.characterFormat = cf;
  66:             _textFlow.flowComposer.updateAllContainers();
  67:         }
  69:         private function changeNoColumns(event:SliderEvent):void {
  70:             var cf:ContainerFormat = new ContainerFormat(_textFlow.containerFormat);
  71:             cf.columnCount = event.value;
  72:             cf.columnGap = 15;
  73:             _textFlow.containerFormat = cf;
  74:             _textFlow.flowComposer.updateAllContainers();
  75:         }
  77:         private function changeTextDirection(event:Event):void {
  78:             _textFlow.direction = ( as ComboBox);
  79:             _textFlow.flowComposer.updateAllContainers();
  80:         }
  82:     ]]>
  83: </mx:Script>
  84:     <mx:VBox x="20" y="20">
  85:         <mx:Canvas id="canvas" width="600" height="400"  backgroundColor="#ffffff" verticalScrollPolicy="auto"/>
  86:         <mx:HBox width="100%">
  87:             <mx:HSlider labels="Font size:" minimum="10" maximum="22" snapInterval="1" change="changeFontSize(event)" enabled="true" />
  88:             <mx:HSlider labels="No of Columns:" minimum="1" maximum="2" snapInterval="1" change="changeNoColumns(event)" enabled="true" />
  89:             <mx:Label text="Text Direction:"/>
  90:             <mx:ComboBox change="changeTextDirection(event)" dataProvider="{directions}"/>
  91:         </mx:HBox>
  92:     </mx:VBox>
  94: </mx:Application>


So, that was my introduction to the Text Layout Framework. If you want to learn more, the first step is to go to the labs page, where you can take a look at the demo application (the one from which I took the screen shots at the beginning of this article). If you click on the small arrow at the top right of this app, you can download the source code for the current panel and see for yourself how it was done. You can also check out this demo, which lets you explore many of the typographic and text layout capabilities of TLF.

You can find the APIs here, and you can download samples for Flash CS4, Flex 3.2, and Gumbo from the labs page.

LATER UPDATE: if you wonder how to add a scrollbar to control the text, read this post.

104 thoughts on “How to use Text Layout Framework in Flex 3.2 or AIR 1.5

  1. Pingback: FLEX{er} » Blog Archive » Two New Adobe Projects Go Open Source - OSMF & TLF

  2. Hi, I am using Flex 3.2 and textlayout_framework_p1_111808 in my project.
    I migrated to textlayout_framework_455 to use external css using CSSFormatResolver but not
    able to use embedded fonts in TLF.
    Please suggest.

  3. Hello, is there a way to run an swf flash file inside text layout framework?

    I mean, suppose your application allows users to enter their own data in a TLF screen (kind of CMS). What if the user wants to add an swf file? Is this possible? If not, is there a work around for this?

    Thanks a lot

  4. I am finding it impossible to have rtl arabic text with linebreak set to explicit. Whenever a rtl text is set with linebreak as explicit it acts like a ltr text. this is extremly problematic…anyone help

  5. Pingback: 在Flex中实现聊天表情图片支持-资料篇 | zrong's Blog

  6. I have : link example into TextFlow

    I need collect the href data to an textInput when the curson is on ‘link example’ words.

    I add a Listener:

    TextFlow.addEventListener(SelectionEvent.SELECTION_CHANGE,selectionChangeListene r,false,0,true);

    and :

    private function selectionChangeListener(evt:SelectionEvent):void

    /// how can I read href tag ?

    myTxt.text = evt ???????



  7. If someone comes up with a TextArea using TLF and includes image wrapping please post it here! Thanks


  8. Hi Guilherme,

    That places the image inline with text on either side but it does not wrap multiple lines of text around the image.

    For example, if an image is higher than the text line height there is a gap between it,





    I’d also like to know if there is a way to give an image it’s own space with no text on either side, I think it’s called float, like this,


  9. The spacing was messed up on the last one. Here is another example of inline (not wrapped),


  10. Hi,
    <span fontWeight=”bold” >
    sample text </span >
    not showing bold text in Linux.
    Please help…..

  11. @judah

    The source is not available for now. You can use TLF with both Flex 3 and Flex 4 (in Flex 4 it is part of the framework, and it easier to used because there are components that are built using TLF).

  12. Pingback: Action Script Error Repository » Error: Unknown element

  13. Pingback: Action Script Error Repository » ArgumentError: newElement not of a type that this can be parent of

  14. Hi

    I had a requirement for text to show as curveup and curvedown. So can i able to make the text curve up and down using textlayout framework.If it is please give some hints.


  15. Hello, i have made a swf which can read text from external xml and create dynamic TLF on stage. This swf works fine as stand-alone or if loaded within another main swf. However, when more than one swf with TLF content is loaded, then i get this error:

    TypeError: Error #1034: Type Coercion failed: cannot convert flashx.textLayout.container::DisplayObjectContainerController@eaabc69 to flashx.textLayout.container.IInternalContainerController.
    at Vector$object/
    at flashx.textLayout.compose::StandardFlowComposer/addController()
    at com.tis::TextImage/parseConfig()
    at com.tis::ResourceObject/completeHandler()
    at MethodInfo-22()

    Individually they work perfect. They work fine if i load only one file. The moment i try to load two files, i get this error. I noticed that the error happens at this line:


    Where am i going wrong?

    Thanks for the valuable post.


  16. I have found the solution for the *TypeError: Error #1034: Type Coercion failed* error listed above. I just had to import the TextLayout swc in the library of the base file too. Just for the record, these are the various libraries/versions I had to use for the implementation:

    * Flash CS4 with Flex SDK
    * TLF_Installed by MXP_11.14.2008 – TextLayout component in the libraries of the base(loader) file and all the FLA files which needs TLF.


  17. hello..
    How to make the inline graphics non selectable.I want that the inline graphic i have inserted in my text should not be get selected by any mean.

  18. hi,
    i read your article but got confused,
    i am trying to change the direction of a tabbed application (tabnavigator).

    how can i do that?


  19. hi
    i am working on the text layout framework and i have a problem with tab key.when i press the tab key the focus from my text area transferred to other components of application rather than to insert a tab (blank spaces) inside the text area.i have written the event for tab key and set the tabEnabled=false for my textarea.

  20. hi
    i am working on the text layout framework and i have a problem with tab key.when i press the tab key it doesn’t insert tab(blank spaces) inside text area.i have written the event for tab key in which i am adding tab element to my paragraph element and also have set tabEnabled=false for all other components inside the application.

  21. Hi,

    I am not able to write a text in Hindi by using the Arial font.
    I tried with or without text layout framework.
    but when i try to write a text in Hindi it will appear as a ‘?’ other than Hindi language i am able to write a text in all languages.

    Please provide me some help. Is flex support Hindi or not.

    Please help me out, i am looking for the solution from the last 1 month.


  22. @Rajesh

    I worked out resizing the text area/layout can be done by adding a resize event handler to the canvas.

    _canvas.addEventListener(ResizeEvent.RESIZE, resizeWindowHandler);

    and in that handler I have the following code.

    _controller.setCompositionSize(_canvas.width, _canvas.height);
    _controller.verticalScrollPosition = _controller.calculateHeight();

    The last line forces the text to always scroll to the last line in the text area. Hope this helps you and anyone else struggling.

  23. Hi, could you tell me how can I update the text insidewithout typing it, let’s suposse I’m justcreating an editor and once I get my text export it somewhere else, then I need to erase that text so I can continue creating other text but wihtout having the user to erase it and start again. Thanks in advance for your response.

  24. Hi Oscar,
    I too want to erase the text of a textlayout component but unable to do so. have u achieved it?

  25. Pingback: How to make Subscripts with Flash’s Text Layout Framework « Wwwebber's Blog

  26. Pingback: How to rotate Text in Flex/AS3 without Embedding | Hiraash's Blog

  27. Excuse me, if I write a text editor, how to judge the current position of the mouse? And insert the picture, how to let words and pictures in the WORD as various formats that are mixed? And I found TextFlow FONT properties of HTML browser display in the FONT size is large deviation, hoping to give directions.

  28. is there a way you can style the hyperlink.. so instead of using underline you use an animation?

  29. hi friends,

    i have experimented the textlayout demo. my requirement about to display arabic text in datagrid columns, combo box. can any one please help me on that. :)

  30. I was looking for how to write arabic in flex, your blog post and sample code is perfect for that :)


  31. I found a lot of fascinating things inside your weblog particularly its discussion. From the tons of comments in your articles, I assume I am not the one one getting all the enjoyment here! sustain the good work.

  32. Pingback: 关于Adobe Flex图文混排的一些学习和资料 |创见未来

  33. Pingback: zeichen ersetzen mit movieclip aus bibliothek - Flashforum

  34. Hi —

    I know I’m late to the TLF party and this original article is almost 2.5 years old, but does most (or all) of the information still pertain to the release of Flash CS5.5?

    Given that there are so many classes to keep track of I would hate to spend time working with outdated information/methods.

    Many thanks!

  35. Pingback: Truncating HTML Text

Leave a Reply