1

How to get text advance (stringWidth) without a Graphics instance in Java?

In the doc examples, stringWidth() is taken from FontMetrics, while FontMetrics is taken from Graphics.

Is it possible to obtain the same without a Graphics?

In the notes below it is said, that Graphics is required because it holds FontRenderContext. But I have FontRenderContext, just have no Graphics.

So, suppose I have FontRenderContext without a Graphics. How do I get stringWidth() then?

Manu
  • 1,474
  • 1
  • 12
  • 18
Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385
  • 1
    Why do you "have FontRenderContext without a Graphics"? This sounds weird. Can you post your code? – Tunaki Sep 28 '15 at 09:10
  • 1
    Essentially, you can't. By necessity, you need a `Graphics` context as it defines the properties to which the font will be rendered and will effect how the calculations are made – MadProgrammer Sep 28 '15 at 09:11
  • @Tunaki I have created frc with `new FontRenderContext(null, isAntiAliased, usesFractionalMetrics)` – Suzan Cioc Sep 28 '15 at 11:52

1 Answers1

5

While "A FontRenderContext which is directly constructed will most likely not represent any actual graphics device, and may lead to unexpected or incorrect results," you can obtain useful metrics from an instance of TextLayout, as shown here and here.

FontRenderContext frc = new FontRenderContext(null, false, false);
TextLayout layout = new TextLayout(text, font, frc);
System.out.println(layout.getBounds());

image

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045