How to determine the length (in pixels) of a string being rendered on a web page?

Asked
Active3 hr before
Viewed126 times

7 Answers

stringdeterminelength
90%

phalacee, I am not able to find a way in GD to determine the string width. It seems that I must call imagecreate() with image width and height params before a string can be written to it thus making the excercise a futile round trip :( – KJ Saxena Oct 29 '09 at 6:25 ,What you can do is determine that width using javascript after the page is rendered (obviously, you can do that in some other page as well and hope nothing changes till then) and submit that back to PHP. With some clever AJAX-ing you can even do this on the same page.,Your title and actual post seem to say slightly different things. I'm guessing what you're really asking is whether it's possible to determine the width in pixels of text rendered on a web page in your PHP code (prior to web page being rendered)., Actually, it is a little bit of both as I am using the SVG definition for an image - the image is not a bitmap. Thus, it is the browser's problem to find the correct font but let's say that the font is definitely available. How do we find the width now? How can I retrieve the pixel width of each glyph in the font and sum? – KJ Saxena Oct 29 '09 at 6:02

If you use this, it should work:

   list($left, , $right) = imageftbbox(12, 0, "arial.ttf", "Hello World");

   $width = $right - $left;
load more v
88%

There are many situations while developing websites when you need to know how long a text string is: not how many characters it has but how long it is in pixels. While this isn't of much importance for regular webdesign it might get useful in certain scenario's like for example when designing Vista Sidebar gadgets.,The next step is to create a function which will measure the length of a text in pixels:,a function for visually trimming the text to the desired length in pixels,The most common scenario I have faced was properly displaying a text string within limited space. If the string is visually longer than the available space it has to be visually trimmed. To let the user know that the text was trimmed ... (three dots) are appended to the string.

<span id="ruler"></span>
load more v
72%

Php – How to determine the first and last iteration in a foreach loop,Javascript – Get the size of the screen, current web page and browser window,Use the PHP function imagettfbbox to get the size of the bounding box for the given string.,Javascript – How to modify the URL without reloading the page

65%

Hide or show elements in HTML using display property,How to insert spaces/tabs in text using HTML/CSS?,How to set input type date in dd-mm-yyyy format using HTML ?,Convert a string to an integer in JavaScript

75%

The Size, in pixels, of text drawn with the specified font and format.,Thrown if ModifyString is set.,The Size, in pixels, of text drawn with the specified font.,The Size, in pixels, of text drawn with the specified font in the specified device context.

public:
   static System::Drawing::Size MeasureText(System::String ^ text, System::Drawing::Font ^ font, System::Drawing::Size proposedSize, System::Windows::Forms::TextFormatFlags flags);
public static System.Drawing.Size MeasureText(string text, System.Drawing.Font font, System.Drawing.Size proposedSize, System.Windows.Forms.TextFormatFlags flags);
public static System.Drawing.Size MeasureText(string ? text, System.Drawing.Font ? font, System.Drawing.Size proposedSize, System.Windows.Forms.TextFormatFlags flags);
static member MeasureText: string * System.Drawing.Font * System.Drawing.Size * System.Windows.Forms.TextFormatFlags - > System.Drawing.Size
Public Shared Function MeasureText(text As String, font As Font, proposedSize As Size, flags As TextFormatFlags) As Size

The following code example demonstrates how to use one of the MeasureText methods. To run this example, paste the code into a Windows Form and call DrawALineOfText from the form's Paint event handler, passing e as PaintEventArgs.

private static void DrawALineOfText(PaintEventArgs e) {
   // Declare strings to render on the form.
   string[] stringsToPaint = {
      "Tail",
      "Spin",
      " Toys"
   };

   // Declare fonts for rendering the strings.
   Font[] fonts = {
      new Font("Arial", 14, FontStyle.Regular),
      new Font("Arial", 14, FontStyle.Italic),
      new Font("Arial", 14, FontStyle.Regular)
   };

   Point startPoint = new Point(10, 10);

   // Set TextFormatFlags to no padding so strings are drawn together.
   TextFormatFlags flags = TextFormatFlags.NoPadding;

   // Declare a proposed size with dimensions set to the maximum integer value.
   Size proposedSize = new Size(int.MaxValue, int.MaxValue);

   // Measure each string with its font and NoPadding value and 
   // draw it to the form.
   for (int i = 0; i < stringsToPaint.Length; i++) {
      Size size = TextRenderer.MeasureText(e.Graphics, stringsToPaint[i],
         fonts[i], proposedSize, flags);
      Rectangle rect = new Rectangle(startPoint, size);
      TextRenderer.DrawText(e.Graphics, stringsToPaint[i], fonts[i],
         startPoint, Color.Black, flags);
      startPoint.X += size.Width;
   }
}
Private Sub DrawALineOfText(ByVal e As PaintEventArgs)
' Declare strings to render on the form.
Dim stringsToPaint() As String = {
   "Tail",
   "Spin",
   " Toys"
}

' Declare fonts for rendering the strings.
Dim fonts() As Font = {
   New Font("Arial", 14, FontStyle.Regular),
   _
   New Font("Arial", 14, FontStyle.Italic),
   _
   New Font("Arial", 14, FontStyle.Regular)
}

Dim startPoint As New Point(10, 10)

' Set TextFormatFlags to no padding so strings are drawn together.
Dim flags As TextFormatFlags = TextFormatFlags.NoPadding

' Declare a proposed size with dimensions set to the maximum integer value.
Dim proposedSize As Size = New Size(Integer.MaxValue, Integer.MaxValue)

' Measure each string with its font and NoPadding value and draw it to the form.
For i As Integer = 0 To stringsToPaint.Length - 1
Dim size As Size = TextRenderer.MeasureText(e.Graphics, _ stringsToPaint(i), fonts(i), proposedSize, flags)
Dim rect As Rectangle = New Rectangle(startPoint, size)
TextRenderer.DrawText(e.Graphics, stringsToPaint(i), fonts(i), _ startPoint, Color.Black, flags)
startPoint.X += size.Width
Next
End Sub
load more v
40%

An even more economical rendering would factor the common information and reorder it:,row: The current cell provides header information for the rest of the row that contains it (see also the section on table directionality).,The following informative list describes what operations user agents may carry out when rendering a table:,Of course, there is no limit to how authors may categorize information in a table. In the travel expense table, for example, we could add the additional categories "subtotals" and "totals".

Here's a simple table that illustrates some of the features of the HTML table model. The following table definition:

<TABLE border="1" summary="This table gives some statistics about fruit
                   flies: average height and weight, and percentage
                   with red eyes (for both males and females).">
   <CAPTION><EM>A test table with merged cells</EM></CAPTION>
   <TR>
      <TH rowspan="2">
      <TH colspan="2">Average
      <TH rowspan="2">Red<BR>eyes
   <TR>
      <TH>height
      <TH>weight
   <TR>
      <TH>Males
      <TD>1.9
      <TD>0.003
      <TD>40%
   <TR>
      <TH>Females
      <TD>1.7
      <TD>0.002
      <TD>43%
</TABLE>

might be rendered something like this on a tty device:

          A test table with merged cells
             /
             -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - \
             |
             | Average | Red |
             |
             | -- -- -- -- -- -- -- -- -- - | eyes |
             |
             | height | weight | |
             |
             -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - |
             |
             Males | 1.9 | 0.003 | 40 % |
             |
             -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - |
             |
             Females | 1.7 | 0.002 | 43 % | \-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - /
load more v
22%

One or more strings separated by commas, indicating a set of source sizes. Each source size consists of:,One or more strings separated by commas, indicating possible image sources for the user agent to use. Each string is composed of:,A string indicating which referrer to use when fetching the resource:,This attribute is also used when copying and pasting the image to text, or saving a linked image to a bookmark.

<img src="favicon144.png" alt="MDN logo">
load more v

Other "string-determine" queries related to "How to determine the length (in pixels) of a string being rendered on a web page?"