Obtaining FontMetrics before getting a Graphics instance
- by Tom Castle
Typically, I'd obtain a graphics instance something like this:
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
However, in the current project I'm working on, the width and height variables above are dependent upon the size of a number of text fragments that will later be drawn onto the graphics instance. But, to obtain the dimensions of the font being used I would usually use the FontMetrics that I get from the graphics object.
FontMetrics metrics = g.getFontMetrics();
So, I have a nasty little dependency cycle. I cannot create the graphics object until I know the size of the text, and I cannot know the size of the text until I have a graphics object. One solution is just to create another BufferedImage/Graphics pair first in order to get the FontMetrics instance I need, but this seems unnecessary.
So, is there a nicer way?
Or is it the case that the width, height etc. properties for a Font are somehow dependent upon what (graphics, component...) the text is to be drawn on?