Skip to main content



      Home
Home » Eclipse Projects » Standard Widget Toolkit (SWT) » getFontMetrics() returns invalid results (The GC .getFontMetrics() returns the the same value regardless of Font.)
getFontMetrics() returns invalid results [message #1853503] Tue, 05 July 2022 17:46
Eclipse UserFriend
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
Previous Topic:Can SWT run on Raspberry Pi 4B?
Next Topic:browser org.eclipse.swt.browser.EdgeDir as a relative path
Goto Forum:
  


Current Time: Wed Jul 09 06:43:52 EDT 2025

Powered by FUDForum. Page generated in 0.07663 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top