Hello,
my problem:
I have a text (singleline) and a fix width for the whole text.
How do I find the correct font (height) for this text?
thx.
Ralf
Printable View
Hello,
my problem:
I have a text (singleline) and a fix width for the whole text.
How do I find the correct font (height) for this text?
thx.
Ralf
Define "correct font".
There might be a lot of fonts with a lot of font sizes that would fit your "fix width" and there might be that no font would fit it!
Hello Victor,
an example:
I need the font "Arial". The width for the text "Hello" shoud be 100px.
How do I find/create it?
- Get the DC of the control.
- Create font Arial with some size.
- Select font in the DC.
- Use some of the CDC methods (like GetTextExtent) to obtain the width of the displayed text.
- Compare it with the predefined width (100px in your example).
- If the obtained width is more than the predefined - decrease font size, if it is less - increase font size, and goto the p.2.
- ...
ok, that is possible.
But no solution for me, because it is a time critical function (I have to obtain the font for many texts).
Maybe I should do this:
I have to pre-calculate the possible fonts for some typical widths.
You can make good estimates based on averages. But if you really need precision and the maximum size the font can be to not exceed the limit, then the solution given by victor is the only solution.
Besides... define 'time critical' ? maybe this solution is fast enough. If you're not actually doing drawing, then this is quite fast. Entire wordprocessors and browser renderers rely on that very feature. Whatever you are trying to precalculate, the built in functions will probably do better/faster.
If you really can't afford a performance hit, consider using a monotype font like courier/consolas. Calculating the width of a tekst is then the width of a single char multiplied by the number of chars.
Hello OReubens,
thank you.
I am doing drawing!
I can not use a monotype font.
Please tell me more about "estimates based on averages". How can I do that?
Ralf
Have a look at CDC::GetTextMetrics
I think you misunderstood me.
Yes, you are actually drawing, but usually once once for a given case.
the testing phase where you "try" different sized fonts, you don't actually draw anything, you're only asking the API's to calculate how much width/height it would take if you did actually draw.
So this is only a calculation of size, not actually manipulating pixels. THe calculations are typically very fast. Actual drawing can be an order of magnitude slower, especially when you're goign to screen and want antialiassed or cleartype text. But like I said, you typically only actually draw once.