Java 使用AWT时文本宽度错误
我目前正在使用Java编写一个新的卡拉OK FX生成器。现在我在实现TextExtents函数时遇到了一个问题:它为字幕文件返回了错误的字符串边界 下面是一个例子: 红色矩形表示程序计算的字符串边界,而红色背景表示xy vsfilter计算的边界 有人知道如何解决这个问题吗。我已经试了好几个小时了,但还是没能再继续下去 这是该功能的当前实现Java 使用AWT时文本宽度错误,java,text,bounds,measure,subtitle,Java,Text,Bounds,Measure,Subtitle,我目前正在使用Java编写一个新的卡拉OK FX生成器。现在我在实现TextExtents函数时遇到了一个问题:它为字幕文件返回了错误的字符串边界 下面是一个例子: 红色矩形表示程序计算的字符串边界,而红色背景表示xy vsfilter计算的边界 有人知道如何解决这个问题吗。我已经试了好几个小时了,但还是没能再继续下去 这是该功能的当前实现 /** * Calculates the text-extents for the given text in the specified * sty
/**
* Calculates the text-extents for the given text in the specified
* style.
* @param style The style
* @param text The text
* @return The extents of the text.
*/
public TextExtents getTextExtents(AssStyle style, String text) {
// Reads the font object from the cache.
Font font = this.getFont(style.getFontname(), style.isBold(), style.isItalic());
// If the font is unknown, return null.
if (font == null)
return null;
// Add the font size. (Note: FONT_SIZE_SCALE is 64)
font = font.deriveFont((float) style.getFontsize() * FONT_SIZE_SCALE);
// Returns other values like ascend, descend and ext-lead.
LineMetrics metrics = font.getLineMetrics(text, this.ctx);
// Calculate String bounds.
Rectangle2D rSize = font.getStringBounds(text, this.ctx);
// Returns the text-extents.
return new TextExtents(
rSize.getWidth() / FONT_SIZE_SCALE,
rSize.getHeight() / FONT_SIZE_SCALE,
metrics.getAscent() / FONT_SIZE_SCALE,
metrics.getDescent() / FONT_SIZE_SCALE,
metrics.getLeading() / FONT_SIZE_SCALE
);
}
我部分解决了这个问题。LOGFONT.lfHeight和Java使用不同的字体大小单位。因此,我必须将java的字体大小转换为逻辑单元
// I used this code to convert from pixel-size to "logical units"
float fontSize = 72F / SCREEN_DPI; // SCREEN_DPI = 96
现在我只有一点不同