我目前正在使用Java编写一个新的卡拉OK-FX-Generator。现在我对TextExtents-Function的实现有一个问题:它为Subtitle文件返回了错误的字符串边界。
这是一个例子:
红色矩形表示由我的程序计算的字符串的边界,而红色背景是由xy-vsfilter计算的边界。
有谁知道如何解决这个问题。我正在尝试几个小时,但我仍然没有进一步。
这是该功能的当前实现。
/**
* 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的font-size转换为“逻辑”单元。
// I used this code to convert from pixel-size to "logical units"
float fontSize = 72F / SCREEN_DPI; // SCREEN_DPI = 96
现在我只有很小的差异。