0

The program I'm making uses string related calculations done with FontMetrics. As FontRenderContext may vary, it is required to make the calculations correctly and I have a static instance of it saved so I can access it anywhere.

I found a way to calculate string width using font and context (without Graphics2D instance):

font.getStringBounds(string, Window.fontRenderContext).getWidth()

The problem I have is calculating descent, ascent and anything else FontMetrics provides. I could:

  • Create a canvas, get its Graphics, apply all of the settings to it and get FontMetrics. It would require a lot of code and it would not work stably as Canvas.getGraphics can arbitrarily return null.
  • Delay those calculations until my paint(Graphics2D g) method is run, where I could get FontMetrics directly.
  • Try to get needed values from Font.getStringBounds. I would doubtfully manage to do it.

It confuses me that I can get getStringBounds just from font and context (getStringBounds consists of FontMetrics values), but it turns into such headache when I need to get original descent, ascent, etc values.

0 Answers0