How to Highlight the Text in Flex(with Full Source Code)

Text-Edit Maybe you have read RegExr: Online Regular Expression sample(www.regexr.com) , the high-light effect of matched characters is perfect and with the mouse moving will show the detail information of the alphabetic string as the following image show. 

clip_image002

Because it adds a DisplayObject into the matched alphabetic string.

Then let’s try to do this effect.  

Search-256x256 Demo | DownloadDownload Full Project

How to locate postion of the high-light and height and width is the important point. We could get the relative data by the  TextField.

1.getLineIndexOfChar(charIndex:int):int
Returns the zero-based index value of the line containing the character specified by the charIndex parameter.

2.getLineOffset(lineIndex:int):int
Returns the character index of the first character in the line that the lineIndex parameter specifies.

3.getLineLength(lineIndex:int):int
Returns the number of characters in a specific text line.

4.getLineIndexOfChar(charIndex:int):int
Returns the zero-based index value of the line containing the character specified by the charIndex parameter.

5.getCharBoundaries(charIndex:int):Rectangle
Returns a rectangle that is the bounding box of the character.

clip_image003

Let’s see another image to understand the structure of flash text.

Pay more attention of the “2-pixel gutter”. If forget adding it to the postion formula, the high light area will be offset by 2 pixels.

Now let’s first consider the position of the high-light area ( the text arranged in this article are limited from left to right ) 

1. The case which selected text block out of the TextField displaying area could be ignored.

clip_image005

2. Selected text block in the TextField displaying area. Devide the selected text block into “single line”. The first line high-light area is from beginIndex to end characters of the first line. The middle lines high-light area is from the line begin to line end. The last line high-light area is from the line begin to endIndex. 

clip_image007

clip_image001

3. Part of the selected text block in the displaying area and part out of the displaying area. Then there are two situation:

1) If the start index value less than the first character of the displaying area then just need to high-light the beginIndex to endIndex as following image.

clip_image010clip_image011

2) If the end index value bigger than the end character of the displaying area then just need to high-light the beginIndex to endIndex as following image.

clip_image013 clip_image015

Summarized as follows:
1. Get the effective biginIndex and endIndex.

2. The single line do the single line high-light.

3. The multi-line do the high-light according the first line, middle line and last line.

When we have known the basic method, built the the new project “HighlightText”

clip_image017 

New built the folder com->kingnare->regex

New built class HighlightBlock under regex folder and superclass choose UIMovieClip.

clip_image019

According the previous idea, we wrote the class Highlight Block:

HighlightBlock.as

Then let’s simply explain the process of the HighlightBlock:

Get the begin and end index of the high-light block in displaying area by the way of getValidBeginCharIndex and getValidEndCharIndex. Then high light the block by normalDraw.

In normalDraw method, get the distance which the imported index value located line relative to the text registration point by getDisLineHeightByLine. It will be convenient to calculate the y coordinate of high-light block.

Then how to use the class?

The access parameter type is IUITextField, but the other internal components like TextArea is protected then need to visit by succession. New built file com->components, new built class BlockTextArea and superclass choose TextArea: clip_image021

The code as below:

  1. package com.components
  2. {
  3. import com.kingnare.regex.HighlightBlock;
  4. import flash.display.DisplayObject;
  5. import flash.geom.Point;
  6. import mx.controls.TextArea;
  7.  
  8. public class BlockTextArea extends TextArea
  9. {
  10. private var blockArray:Array;
  11. public function BlockTextArea()
  12. {
  13. super();
  14. blockArray = [];
  15. }
  16.  
  17. public function showBlock(beginIndex:int, endIndex:int):void
  18. {
  19. var movieTip:HighlightBlock= new HighlightBlock(this.textField);
  20.  
  21. movieTip.offsetPoint = new Point(0, 0);
  22. movieTip.highLightDraw(beginIndex, endIndex);
  23. movieTip.toolTip = “beginIndex: “+beginIndex+“\nendIndex: “+endIndex+“\nlength: “+(endIndex-beginIndex+1).toString()+“\ntext:\t”+this.textField.text.substring(beginIndex, endIndex+1);
  24.  
  25. clearBlock();
  26. this.addChild(movieTip);
  27. blockArray.push(movieTip);
  28. }
  29.  
  30. public function clearBlock():void
  31. {
  32. var len:uint = blockArray.length;
  33. for(var k:uint=0;k<len;k++)
  34. {
  35. var obj:DisplayObject = blockArray[k]
  36. this.removeChild(obj);
  37. obj = null;
  38. }
  39.  
  40. blockArray = [];
  41. }
  42. }
  43. }

Switch to the HighlightTest.mxml, set the height and width of the main program is 160×420 and new add a component BlockTextArea. Then add other components.

  1. <components:BlockTextArea id=”lightTextwidth=”400height=”100y=”10x=”10/>
  2. <mx:Button y=”118label=”Show Highlightright=”10/>
  3. <mx:TextInput id=”beginIndexInputx=”92y=”118width=”60/>
  4. <mx:TextInput id=”endIndexInputx=”232y=”118width=”60/>
  5. <mx:Label x=”10y=”121text=”beginIndex:/>
  6. <mx:Label x=”160y=”121text=”endIndex:/>

Switch to the Design panel:

clip_image023

Next add ActionScript code for the main program.

First is the event applicationComplete of Application. 

  1. <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxmllayout=”absolutexmlns:components=”com.components.*”
  2. width=”420height=”160applicationComplete=”initApp();”>

Next write the initApp in ActionScript:

  1. private function initApp():void
  2. {
  3. }

In this way we initialize the lightText, beginIndexInput, endIndexInput and add the ScrollEvent’s Listener of lightText.

  1. import mx.events.ScrollEvent;
  2. import mx.managers.ToolTipManager;
  3.  
  4. private function initApp():void
  5. {
  6. //ToolTip display immediately
  7. ToolTipManager.showDelay = 0;
  8. lightText.addEventListener(ScrollEvent.SCROLL, scrollEvent);
  9. lightText.htmlText = “Documentation for classes includes syntax, “ +
  10. “<b><font size=’18′>usage</font></b> information, and code samples for methods, “ +
  11. properties, “ +
  12. and event handlers and listeners for those APIs that belong to a specific class “ +
  13. in ActionScript (as opposed to global functions or properties). “ +
  14. The <font size=’24′>classes</font> are listed alphabetically. “ +
  15. “If you are not sure to which class a certain method or property belongs, “ +
  16. “you can look it up in the Index.”;
  17.  
  18. beginIndexInput.text = “43″;
  19. endIndexInput.text = “300″;
  20. }

Complete the click way of “show highlight” button as the way of high-light displaying. 

  1. private function showBlock():void
  2. {
  3. lightText.showBlock(parseInt(beginIndexInput.text), parseInt(endIndexInput.text));
  4. }

In order to update the high-light block immediately, we need to add a timer. When the text changed, call the showBlock to redraw the high-light block. The final code as below. 

  1. <?xml version=”1.0encoding=”utf-8?>
  2. <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxmllayout=”absolutexmlns:components=”com.components.*”
  3. width=”420height=”160applicationComplete=”initApp();”>
  4. <mx:Script>
  5.  
  6. <![CDATA[
  7. import mx.events.ScrollEvent;
  8. import mx.managers.ToolTipManager;
  9. private var updateTimer:Timer;
  10. private function initApp():void
  11. {
  12. ToolTipManager.showDelay = 0;
  13. //timer
  14. updateTimer = new Timer(5, 1);
  15. updateTimer.addEventListener(TimerEvent.TIMER, validate, false, 0, true);
  16. lightText.addEventListener(ScrollEvent.SCROLL, scrollEvent);
  17. lightText.htmlText = "Documentation for classes includes syntax, " +
  18. "<b><font size='18'>usage</font></b> information, and code samples for methods, " +
  19. "properties, " +
  20. "and event handlers and listeners for those APIs that belong to a specific class " +
  21. "in ActionScript (as opposed to global functions or properties). " +
  22. "The <font size='24'>classes</font> are listed alphabetically. " +
  23. "If you are not sure to which class a certain method or property belongs, " +
  24. "you can look it up in the Index.";
  25.  
  26. beginIndexInput.text = "43";
  27. endIndexInput.text = "300";
  28. }
  29.  
  30. private function showBlock():void
  31. {
  32. lightText.showBlock(parseInt(beginIndexInput.text), parseInt(endIndexInput.text));
  33. }
  34.  
  35. //validate
  36. private function validate(event:TimerEvent):void
  37. {
  38. showBlock();
  39. }
  40.  
  41. //scrollEvent
  42. private function scrollEvent(event:ScrollEvent):void
  43. {
  44. updateBlock();
  45. }
  46.  
  47. //update
  48. private function updateBlock():void
  49. {
  50. updateTimer.reset();
  51. updateTimer.start();
  52. }
  53.  
  54. ]]>
  55. </mx:Script>
  56. <components:BlockTextArea id=”lightTextwidth=”400height=”100y=”10x=”10/>
  57. <mx:Button y=”118label=”Show Highlightclick=”showBlock();” right=”10/>
  58. <mx:TextInput id=”beginIndexInputx=”92y=”118width=”60/>
  59. <mx:TextInput id=”endIndexInputx=”232y=”118width=”60/>
  60. <mx:Label x=”10y=”121text=”beginIndex:/>
  61. <mx:Label x=”160y=”121text=”endIndex:/>
  62. </mx:Application>

Then we start to test. Click the button “Debug”:

clip_image025

Click the button “Show Highlight”, you will find the blue high-light area:

clip_image027

When the rolling bar roll, it will call the way updateBlock. Redraw the high-light block by calling showBlock after 5ms.

clip_image029

( If beginIndex less than 0 or endInder bigger or equal to the text length. or endIndex less than beginIndex, it will not show the high-light block.)

If you feel the display method is too rigid, you could change the drawBlock in HighlightBlock or rewrite the drawBlock to create the effect such as wave line, underscores and etc.

If change the type of _textField from IUITextField to TextField and do relative change, the class HighlightBlock also could be applicated in ActionScript Project.

OK, now we have finished introducing the how to write and the use of method of HighlightBlock.

Cheers.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Reddit
  • Technorati
  • StumbleUpon
  • Twitter
RSS Enjoy this Post? Subscribe to Ntt.cc

RSS Feed   RSS Feed     Email Feed  Email Feed
You can leave a response, or trackback from your own site.

12 Responses to “How to Highlight the Text in Flex(with Full Source Code)”

  1. Very nice tutorial

  2. [...] Cheers. Permalink:http://ntt.cc/2008/07/20/how-to-highlight-the-text-in-flex-with-full-source-code.html [...]

  3. [...] 注:本文英文版本:How to Highlight the Text in Flex(with Full Source Code) [...]

  4. neel says:

    hi
    sorry for the comment on the unappropriate post.
    i want some sample code which generates the mxml file from database. i have to create different dyanamic forms to create the request.

    can u please help me the same?

    any help appriciated.

    thanks
    shripad

  5. Thomas says:

    Thanks, really good stuff! I was really getting desperate about how to get TextField functions (getCharIndexAtPoint …) into a Flex app. Probably sounds trivial to you but I still haven’t fully understand all those conversions between TextFields, UIComponents and IUIComponents. Your example was really helpful to get this to work!

  6. stephen says:

    very good tutorial. the technique used was very similar to flexlib’s (http://code.google.com/p/flexlib/) highlighter class which was also using TextField. I have two questions: I’m wondering if its possible to accomplish the same effect on Text field and how hard is it and 2) Would your highlighter work on an Itemrenderer where you have a scrolling display / variable widths/heights? flexlib doesnt.

  7. stephen says:

    I meant Text class as opposed to TextField class

  8. Roms says:

    Would it be possible to apply this effect (block + custom tooltip) upon separate sentences of text into the same BlockTextArea ? This is what I’m actually looking for :D

  9. Roms says:

    In fact, I found out how to do it ! Thanks again for your explanations :)

  10. Atul Kulkarni says:

    Hi,

    Nice tutorial..
    sorry for the comment on the unappropriate post.
    Can we do same highlight for
    swf file created with pdf2swf -f optoin.

    can u please help me the same?

    any help appriciated.

    Thanks
    Atul

  11. [...] How to Highlight the Text in Flex(with Full Source Code) – Ntt.cc [...]

Leave a Reply