Skip to main content
July 11, 2014
Answered

How to measure/scale text to fit desired width?

  • July 11, 2014
  • 3 replies
  • 2247 views

I would like to measure the width of a given word or words (not a paragraph) when rendered with a given font and font size. Let's say I have the code below that creates a new document, layer, and text:

var myDoc = app.documents.add(200, 200);


var textLayer = myDoc.artLayers.add();

textLayer.kind = LayerKind.TEXT;

var text = textLayer.textItem;

text.font = "Impact";

text.size = 72;

text.position = Array(100,100);

text.contents = "SUPER";

I want to measure the width of text.

Ultimately I want to resize the text to be a certain width while maintaining its aspect ratio. (The height of the text is not important, just the width, and it should not be distorted.) Knowing the width I could easily calculate the correct font size. If there is a better way to this solution than measuring the width, please let me know.

Thanks!

This topic has been closed for replies.
Correct answer c.pfaffenbichler

The layer has a property "bounds" from which you can calculate the width.

var width = textLayer.bounds[2] - textLayer.bounds[0];

3 replies

Participating Frequently
October 8, 2017

And what's about  "resize the text to be a certain width while maintaining its aspect ratio"?

c.pfaffenbichler
Community Expert
Community Expert
October 8, 2017

What about it?

Participating Frequently
October 8, 2017

How is it possible change width of text to fit desired width?

Inspiring
July 11, 2014

There is no relationship between point/pixel size and character width…

I don't think there is an alternative to set, measure and calculate…

c.pfaffenbichler
Community Expert
c.pfaffenbichlerCommunity ExpertCorrect answer
Community Expert
July 11, 2014

The layer has a property "bounds" from which you can calculate the width.

var width = textLayer.bounds[2] - textLayer.bounds[0];