开发者

Obtaining FontMetrics before getting a Graphics instance

开发者 https://www.devze.com 2022-12-29 02:22 出处:网络
Typically, I\'d obtain a graphics instance something like this: BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

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?


Maybe you can try to get a Graphics instance from some other place. For example, the panel on which the image will be painted on. Then you can get a FontMetrics instance using that Graphic instance.

0

精彩评论

暂无评论...
验证码 换一张
取 消