GreenSock


TextMetrics – Find substring coordinates, line widths, and much more

Posted in Text by jack on the August 7th, 2007
Version 1.6, Updated 1/29/2008
  • Compatibility: Flash Player 8 and later (ActionScript 2.0)
  • File Size added to published SWF: About 1Kb

Download Now
 
Donate

Join Club GreenSock to get updates and a lot more

DESCRIPTION

Have you ever needed to find out where the line breaks occur in a dynamic TextField? How about the precise x/y coordinates of a particular phrase/string along with its width & height so that you could highlight it somehow? Or maybe the width of each line of text? That's all possible with the gs.utils.text.TextMetrics class. And to be consistent with the getTextLineMetrics() function in the TextField AS3 class, it also returns the descent, ascent, and leading values too. You must publish to Flash 8 or later for accurate results. HTML text isn't supported. And for right now, phrases/sentences that span multiple lines aren't supported - the measurements you get back indicate where the first part of the phrase/sentence starts. Justified text is not supported either.

Forums

USAGE

TextMetrics.getSubstringMetrics(textField_tf:TextField, substring_str:String):Array
  • Description: Finds all instances of a particular substring in the TextField and returns an object for each one with the following properties: x, y, width, height, lineHeight, leading, ascent, descent
  • Parameters:
    1. textField_tf: The TextField containing the substring
    2. substring_str: The substring for which you're searching
TextMetrics.getLineMetrics(textField_tf:TextField):Array
  • Description: Goes through each line of a TextField, measures its width and height and it's x and y coordinates and returns an array of objects (one for each line). The objects have the following properties: x, y, width, height, leading, ascent, descent, and text
  • Parameters:
    1. textField_tf: The TextField you're measuring
TextMetrics.getTextBounds(textField_tf:TextField):Object
  • Description: Returns an object with the xMin, xMax, yMin, and yMax, x, y, textWidth, and textHeight of the TEXT inside of a TextField (NOT the TextField box itself)
  • Parameters:
    1. textField_tf: The TextField whose text you're measuring

EXAMPLES

To put a red box over every instance of the word "ActionScript" in the TextField named my_tf, do:

Actionscript:
  1. import gs.utils.text.TextMetrics;
  2. var instances_array = TextMetrics.getSubstringMetrics(my_tf, "ActionScript");
  3. var instance;
  4. for (var i = 0; i <instances_array.length; i++) {
  5.     instance = instances_array[i];
  6.     box(this, instance.x, instance.y, instance.width, instance.height);
  7. }
  8. function box(parent, x, y, width, height):MovieClip {
  9.     var l = parent.getNextHighestDepth();
  10.     var mc = parent.createEmptyMovieClip("box"+l, l);
  11.     mc.beginFill(0xFF0000);
  12.     mc.moveTo (0, 0);
  13.     mc.lineTo (width, 0);
  14.     mc.lineTo (width, height);
  15.     mc.lineTo (0, height);
  16.     mc.lineTo (0, 0);
  17.     mc.endFill();
  18.     mc._x = x;
  19.     mc._y = y;
  20.     mc._alpha = 50;
  21.     return mc;
  22. }

FAQ

  1. Does this class measure text perfectly in every scenario?
    In my tests thus far, as long as you publish to Flash 8 or later, it has proven to be extremely reliable. That being said, Flash is known for rather buggy and inaccurate text mesurement. You might run into situation where this class doesn't perform perfectly but I'm not aware of any specific problems/issues. Please let me know if you run into any.
  2. Do I need to embed fonts for this to work?
    Nope. It seems to work just fine with or without embedded fonts.

Need Help?

Feel free to e-mail me a question. Or post your question on the new forums. I'd highly recommend joining Club GreenSock to get prioritized access to my time in answering your question, and so that you receive updates and lots more. When you e-mail your question, please include a simplified FLA file (and any class files) that clearly demonstrates the problem and provide a brief explanation.

PERMISSION

TextMetrics is free. You're welcome to use it for commercial purposes - I only ask that you consider joining Club GreenSock. As the classes have gained popularity, I must admit that I've been a little overwhelmed by the amount of time it has taken to answer questions and continue development. Less than 1/100th of one percent of my blog visitors donate anything, so it has been difficult justifying the time away from billable jobs (of which there's no shortage!). I really LOVE writing classes like this, and if I could do it all day everyday, I would. But without enough donations, it's just not realistic.

Author: Jack Doyle, (e-mail: jack -at- greensock.com)
Copyright 2008, GreenSock (This work is subject to the terms here.)

To download the code, you must agree to the following license:

Copyright 2008, GreenSock, Inc.

"NO CHARGE" NON-EXCLUSIVE SOFTWARE LICENSE AGREEMENT

-----------------------------------------------------------------------------
PLAIN ENGLISH SUMMARY:

  1. You may use the code at no charge in web sites, games, components, applications, and other software as long as end users are not charged a fee of any kind to use your product or gain access to it. It doesn’t matter if you are paid to create the site/product. If you charge end users a fee, you must sign up for a corporate Club GreenSock membership which comes with a commercial license granting you permission to do so. See http://blog.greensock.com/club/ for details.
  2. Since the code is updated frequently and developers are best served by having the latest version, please avoid (or at least minimize) distributing the source code outside your organization.
  3. Use at your own risk. I offer no warranties.
  4. Please respect the copyright.

-----------------------------------------------------------------------------

LEGALESE:

This is a legal agreement between you (either an individual or a single entity) and GreenSock, Inc. ("GREENSOCK") for the proprietary GreenSock ActionScript code known as TweenLite, TweenFilterLite, TweenMax, TweenGroup, OverwriteManager, and other code that is freely available for download at http://blog.greensock.com or http://www.greensock.com (this code and documentation, as well as any updates which may at GREENSOCK's sole discretion be provided to you from time to time, are referred to in this Agreement as "PROGRAM") By installing, copying, or otherwise using the PROGRAM, you agree to the terms and conditions of this Agreement. If you do not agree to the terms and conditions of this Agreement, please do not install or use the PROGRAM.

I. LICENSE
A. Subject to the terms and conditions of this Agreement, GREENSOCK hereby grants you a non-exclusive, worldwide, non-transferable right to use the PROGRAM in web sites, games, applications, components and other software for which the end user is NOT charged any fees. If you would like to use the code in a commercially licensed software product for which end users are charged a fee (either for usage or access), simply sign up for a corporate Club GreenSock membership at http://blog.greensock.com/club/.

II. LIMITATION OF LICENSE AND RESTRICTIONS
A. You agree that you will not disclose, sell, rent, license, or otherwise distribute the PROGRAM's source code or any derivative works thereof to any third party without the prior written consent of GREENSOCK. Derivative works are defined as modifications that add substantive functionality to the PROGRAM and do not include bug fixes or other minor modifications required to operate the PROGRAM as originally intended. Limited distribution of the source code to vendors as part of your Work Product is acceptable so long as they agree to the terms of this Agreement. You agree not to modify or delete GreenSock's existing copyright notice located in the source code.

B. You may use, duplicate, and distribute the compiled object code solely as embedded in a Work Product created by you, either for your own use or for distribution to a third party so long as end users of the Work Product are not charged a fee for usage. Please see http://blog.greensock.com/licensing/ for descriptions of Work Products that qualify for the "No Charge" license.

III. CONSIDERATION
A. The license rights granted to you under this Agreement are at no charge, but only in the following circumstances: If, either on your own behalf or on behalf of a third party, you incorporate the Software into a web site, software application, program or any component thereof (collectively, “Work Product”), which in the case of a web site, must be accessible to internet users without payment of a fee of any kind by a user, and in the case of a software application, program or component, neither you nor anyone to whom you distribute the Work Product charges a user a fee of any kind to use such Work Product or application, program or component into which such Work Product is embedded. The foregoing shall apply regardless of whether you are paid to create such Work Product and, under any circumstances, shall be subject to the prohibition against distribution of Source Code set forth in Section II.

B. In the event your intended use of the Software does not meet the criteria for the “no charge” license rights set forth in the immediately preceding paragraph, then you are not licensed to use the PROGRAM under this Agreement and must license the PROGRAM under GreenSock’s separate fee-based Software License Agreement which is granted to corporate Club GreenSock members (see http://blog.greensock.com/club/ for details).

IV. TITLE AND OWNERSHIP
A. The PROGRAM is licensed, not sold, and is protected by copyright laws and international treaty provisions. You acknowledge that no title to the intellectual property in the Software is transferred to you. You further acknowledge that title and full ownership rights to the PROGRAM, including all intellectual property rights therein, will remain the exclusive property of GreenSock and you will not acquire any rights to the PROGRAM except as expressly set forth in this Agreement. You agree that any copies of the PROGRAM you make will contain the same proprietary notices which appear on and in the PROGRAM.

V. DISCLAIMER OF WARRANTY AND LIMITATION OF LIABILITY
A. THE PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. GREENSOCK DOES NOT WARRANT THAT THE FUNCTIONS CONTAINED IN THE PROGRAM WILL MEET YOUR REQUIREMENTS OR THAT OPERATION WILL BE UNINTERRUPTED OR ERROR FREE. GREENSOCK shall not be liable for special, indirect, incidental, or consequential damages with respect to any claim on account of or arising from this Agreement or use of the PROGRAM, even if GREENSOCK has been or is hereafter advised of the possibility of such damages. Because some states do not allow certain exclusions or limitations on implied warranties or of liability for consequential or incidental damages, the above exclusions may not apply to you. In no event, however, will GREENSOCK be liable to you, under any theory of recovery, in an amount in excess of the license fee paid by you under this Agreement. Notwithstanding anything else in this agreement, you agree to indemnify GREENSOCK, its assignees, and licensees, and hold each of them harmless from and against any and all claims, demands, losses, damages, liabilities, costs, and expenses, including legal fees.

B. GREENSOCK may, at its sole discretion, provide support services related to the PROGRAM, but has no obligation to do so.

VI. TERMINATION
GreenSock may terminate this Agreement at any time if you fail to comply with the terms and conditions of this Agreement.

VII. MISCELLANEOUS
A. This Agreement shall be construed in accordance with the laws of the State of Illinois. Should you for any reason bring a claim, demand, or other action against GREENSOCK, its agents or employees, arising out of this Agreement or the PROGRAM licensed herein, you agree to bring said claim only in the Illinois Court of Claims.

B. THIS AGREEMENT REPRESENTS THE COMPLETE AND EXCLUSIVE STATEMENT OF THE AGREEMENT BETWEEN GREENSOCK AND YOU AND SUPERSEDES ALL PRIOR AGREEMENTS, PROPOSALS, REPRESENTATIONS AND OTHER COMMUNICATIONS, VERBAL OR WRITTEN, BETWEEN THEM WITH RESPECT TO USE OF THE PROGRAM. THIS AGREEMENT MAY BE MODIFIED ONLY WITH THE MUTUAL WRITTEN APPROVAL OF AUTHORIZED REPRESENTATIVES OF THE PARTIES.

C. The terms and conditions of this Agreement shall prevail notwithstanding any different, conflicting, or additional terms or conditions which may appear in any purchase order or other document submitted by you. You agree that such additional or inconsistent terms are deemed rejected by GREENSOCK.

D. GREENSOCK and you agree that any xerographically or electronically reproduced copy of this Agreement shall have the same legal force and effect as any copy bearing original signatures of the parties.

I'd like to donate & get bonus classes, update notifications, SVN access, and more.

15 Responses to 'TextMetrics – Find substring coordinates, line widths, and much more'

Subscribe to comments with RSS


  1. on August 9th, 2007 at 4:28 pm

    Thanks! This one save me a TON of coding & debugging tonight!

  2. Dan Efergan said,

    on August 16th, 2007 at 8:54 am

    Thanks. I was about to set about working out the same, but you’ve already done it and a whole lot more! I’m looking forward to seeing how you went about it.

  3. Adam said,

    on September 7th, 2007 at 4:36 pm

    This class is great, thanks a lot!

  4. karim said,

    on September 18th, 2007 at 1:31 pm

    very nice one indeed.
    Thanks for the effort

  5. Martin said,

    on September 23rd, 2007 at 5:34 pm

    Darn, I can’t believe it! You’ve found the answer to this utterly frustrating riddle: “what’s my text’s width and height”. All of these functionalities declined for lack of better measurement capabilities. I can’t wait to use this class!

    Thanks man.


  6. on November 21st, 2007 at 12:50 pm

    thanks for the GREAT post! Very useful…

  7. ... said,

    on December 3rd, 2007 at 7:20 am

    when you add more lines and scroll the text, it will not work properly

  8. jack said,

    on December 4th, 2007 at 10:49 am

    Yes, TextMetrics isn’t meant to track TextFields that are changing/scrolling on a continual basis – it determines the metrics at the point when you call it. So if your TextField changes positions or scrolls or repopulates, you should measure it again.

  9. gamecreature said,

    on December 31st, 2007 at 9:24 am

    Thank you very much!!
    Works very nice!

  10. Jake said,

    on January 28th, 2008 at 1:21 pm

    Great class Jack, very useful.

    I did have one problem with it when I tried to implement the getLineMetrics method. It worked fine for some textfields, but for some it would give each line’s x value as the same as the top line. It turned out that for some of these textfields ‘newline’ was being input as undefined. I replaced ‘newline’ with “\n” and it worked fine.

    And before you ask I have no idea exactly what these different textfields had in common, totally baffling! Just in case anyone else has the same issue.

    Jake

  11. jack said,

    on January 30th, 2008 at 11:46 am

    Thanks for the suggestion, Jake. I updated the class to include “\n” instead of “newline”.

  12. Andrew Merskin said,

    on April 3rd, 2008 at 12:05 pm

    Jack,

    This is JUST what I was looking for… did God give you the title of “Most useful Flash class maker”?

    An ActionScript 3 version would be lovely!

    ~ Andew

  13. Fats said,

    on October 23rd, 2008 at 10:52 pm

    Wow… i love you.
    thanks for the class !

  14. PlugFour said,

    on March 14th, 2009 at 2:03 am

    You are a beast guy! I wish I knew this existed for the past couple years.

  15. Agustín said,

    on April 15th, 2009 at 10:47 pm

    DUDE!!! thanks yet again… I just keep bumping in your classes out of need, and they are always the bes and easier solution… you should apply to Adobe and teach them a bit about what a designer/developer needs.

    or better yet, get some funding from Adobe and keep your awesome work, it’s because of you that Flash keep getting easier and easier to work with.

    I totally agree with Andrew: “Most useful Flash class maker”

Leave a Reply