views:

439

answers:

2

Hi,

I am looking for a function which should take parameters as Font name, sample character, width, height of the sample character and should return Font Size.

It must look like this:

    GetFontSize(<Font Name>, <Sample Character>, <Sample Character Width>,
                <Sample Character Height>)

which must return the font size,

Is this possible in delphi?

+1  A: 

I'm only aware of methods to do the opposite - that is, to get pixel sizes from point sizes.

The only way I can think of is to set up a TCanvas, and repeatedly call GetTextExtent on it, changing the font size each time, until you get a size that's acceptably close to what you want.

Depending on how accurate you need this, you could just convert your desired height in pixels to points - a point is 1/72 of an inch, and your screen is probably 96 pixels per inch (but check GetDeviceCaps to get the real figure). See this question.

That would get you a font size pretty close to the pixel size you want.

Blorgbeard
Thank you Blorgbeard for your reponse. I will check that
Bharat
+2  A: 

You may want to take a look at this page that discusses font size and points.

It uses the following to convert between the points and pixel size:

Arial 12pt at 96 dpi:

                      font size in points             12
font size in pixels = ------------------- × 96 dpi = ---- × 96 = 16 pixels
                      72 points per inch              72

You could use that for your conversion. You just need to be aware of possible differences in your screen dpi as Blorgbeard stated. Points are usually used to describe the size on paper. You need to decide how you want to map that to the screen. For example many programs will allow you to set a zoom level. That does not change the printed size on paper but does affect the pixel height on the screen.

Depending on what you are trying to accomplish you may need to get the actual sizes of the font. If you are trying to find out exactly how the font is put together take a look at Obtaining Font Metrics The code on that page uses the .Net libraries but it has a good explanation. If you want to get the Text Metrics in Delphi you would use the GetTextMetrics function.

As Rob stated in his comment you can draw text at a specific height by setting the Font.Size property to the negative height in pixels. Windows will then draw the text out at that height. In that case you don't need a specific letter or the width as you have in your prototype function. For a given font size each letter will have a different height and width. I.E. capital letters will be taller than lower case letters and letters like "W" will be wider than letters like "i".

Mark Elder