我正在尝试在我的框架/组件上绘制一个大的“hello world”。 但我想动态地适应窗口大小。所以每次我调整窗口大小时,文本应该完全适合窗口。
我使用 FontMetrics 类,并为其分配字体并测量字符的宽度和高度。
但是最好有一个方法,我用文本传递组件的大小,然后该方法返回我需要使用的字体。好吧,特定字体的字体大小就足够了。
像这样:
public int getFontSizeForDrawArea( int width, int height, String text, Font font) {
//Pseudo class FontMeasureClass takes a font to do the measures with
FontMeasureClass measure = new FontMeasureClass( font);
// method takes size of frame/component and text to return the needed
// font size to fit text to frame/component
return measure.getFontSize( width, height, text);
}
我想制作一种方法来测量文本的大小,方法是循环尝试直到文本的大小尽可能接近窗口的宽度和高度。但也许有一些东西可以使用。
最佳答案
您可以计算宽度并用大字体绘制文本,然后使用 Graphics2D.scale
调整它的大小。通常,paintComponent-Method 接收一个 Graphics2D 对象,因此您可以将获取的 Graphics 对象转换为 Graphics2D。
关于Java:如何将绘制的文本动态地适合窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4657918/