Java-调整字体大小以适应区域



多年来,我多次遇到调整中文本大小以适应Java GUI上某个区域的问题。我的解决方案通常是通过以下方式解决问题:

  • 重新设计接口以避免问题

  • 更改区域以适应文本的大小

  • 进行二进制搜索以找到适合字符串的正确大小的字体(当我不能做前两个)

最近在处理另一个项目时,该项目需要快速确定给定区域的正确字体大小,但我的二进制搜索方法太慢(我怀疑是因为创建和测量字体时需要多次按顺序进行动态内存分配),并给我的应用程序带来了明显的滞后。我需要的是一种更快速、更简单的方法来计算字体大小,使给定的字符串能够呈现在GUI的定义区域内。

最后,我想到有一种更简单、更快的方法,只需要在运行时进行一些分配。这种新方法消除了对任何类型搜索的需要,只需要进行一次测量,然而,它确实需要做出一个假设,一个对大多数应用来说完全合理的假设。

  • 字体的宽度和高度必须与字体的点大小成比例。除了对渲染上下文进行的最模糊的转换外,其他所有转换都会发生这种情况

使用这个假设,我们可以计算字体大小与点大小的比率,并线性外推以找到给定区域所需的字体大小。我写的一些代码如下:

编辑:初始测量的准确性受基本字体大小的限制。使用一个非常小的字体大小作为基础可能会产生结果。但基本字体的大小越大,线性近似就越准确。

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Shape;
import java.awt.font.GlyphVector;
import java.awt.geom.Rectangle2D;
public class FontUtilities
{   
public static Font createFontToFit
(
String value,
double width,
double height,
Font base,
Graphics context
)
{
double measuredWidth;
double measuredHeight;
double baseFontSize;
FontMetrics ruler;
Rectangle2D bounds;
double heightBasedFontSize;
double widthBasedFontSize;
GlyphVector vector;
Shape outline;
if
(
(value == null) ||
(base == null) ||
(context == null) ||
(width != width) ||
(height != height)
)
{
return null;
}
//measure the size of the string in the current font size
baseFontSize = base.getSize2D();
ruler = context.getFontMetrics(base);

vector = base.createGlyphVector(ruler.getFontRenderContext(), value);
//use the bounds measurement on the outline of the text since this is the only
//measurement method that seems to be bug free and consistent in java
outline = vector.getOutline(0, 0);
bounds = outline.getBounds();
measuredWidth = bounds.getWidth();
measuredHeight = bounds.getHeight();
//assume that each of the width and the height of the string
//is proportional to the font size, calculate the ratio
//and extrapolate linearly to determine the needed font size.
//should have 2 font sizes one for matching the width, and one for
//matching the height, return the least of the 2
widthBasedFontSize = (baseFontSize*width)/measuredWidth;
heightBasedFontSize = (baseFontSize*height)/measuredHeight;
if(widthBasedFontSize < heightBasedFontSize)
{
return base.deriveFont(base.getStyle(), (float)widthBasedFontSize);
}
else
{
return base.deriveFont(base.getStyle(), (float)heightBasedFontSize);
}
}
}

最新更新