Wrong text width using AWT
Question
I'm currently writing a new Karaoke-FX-Generator using Java. Now I have a problem with the implementation of the TextExtents-Function: It returns the wrong string bounds for the Subtitle file.
Here's an example:
The red rectangle represents the bounds of the string calculated by my program while the red background are the bounds calculated by xy-vsfilter.
Does anyone know how to fix that. I'm trying several hours and I still don't get any further.
This is the current implementation of the function.
/**
* 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
);
}
I partially solved the problem. LOGFONT.lfHeight
and Java uses different unit for font sizes. As such, I had to convert the font-size of java to the "logical" units.
// I used this code to convert from pixel-size to "logical units"
float fontSize = 72F / SCREEN_DPI; // SCREEN_DPI = 96
Now I only have small differences.
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow