getFontMetrics() returns invalid results [message #1853503] |
Tue, 05 July 2022 21:46 |
Yigal Spinner Messages: 130 Registered: July 2009 |
Senior Member |
|
|
I have an application that needs to create Rectangles based on the on the estimated length of a future string. For example if the user sets a length 8, then the rectangle should be large enough to fit any string of 8 characters (any character set or Font).
I used teh GC.getFontMetrics() to get the average character width in current font and character set and calculate the pixel size of the rectangle width. !!!However the value is always much smaller then needed!!!
I create a simple test code:
public class TestMetrics extends AbstractHandler {
private static final String CHATSET="0987654321ABCDEFGHIJKLMNOPQRSTVUWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()-_=+;:/<>~";
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
Shell sh = HandlerUtil.getActiveShell(event);
FontData fontDt = new FontData("Arial", 10, SWT.NORMAL);
calcSizes (fontDt, sh);
fontDt = new FontData("Arial", 10, SWT.BOLD);
calcSizes (fontDt, sh);
return null;
}
private void calcSizes(FontData fontData, Shell sh) {
Font font = new Font(null, new FontData[] {fontData});
GC gc = new GC(sh);
gc.setFont(font);
Point p = gc.textExtent(CHATSET);
FontMetrics fm = gc.getFontMetrics();
gc.dispose();
System.out.format ("Font avg width: %.2f, calc width: %.2f %n", fm.getAverageCharacterWidth(), (double)p.x / (double)CHATSET.length());
}
}
The results are:
1. Regular Font
------> Font avg width: 6.00, calc width: 7.21
2. Bold Font
-------> ont avg width: 6.00, calc width: 7.54
It is clear that "getAverageCharacterWidth()" returns the same value (6.0) which is smaller than needed and it is the same for any font used.
If I use my calculated average,( i.e. Get the size of a String with a set of characters and calculate average) the required average size is valid, however, this does not take in account Character Set. (I used only English Letters)
How can I get the real average width of the current Character Set and Font that the user is using?
Is this bug????
Thanks
Yigal
|
|
|
Powered by
FUDForum. Page generated in 0.03206 seconds