# Set font size based on the height of a REALbasic.Rect

Hi,

I have a tricky question today - at least it’s for me

Let’s say I know the dimensions of a circumscribing rectangle (REALbasic.Rect).
How can I determine the text size of a Graphics object depending on the size of the circumscribing rectangle?

So let’s just say I have a rectangle with a height of 150 pixels. Now I want to draw a letter before the rectangle using Graphics.DrawString that has the height of the rectangle.

Any help would be very welcome.

Thanks.

are you asking what font size to USE?
Normally I set textsize to 0.75 * rect.height

No, if you look at the graphic in my first post, you will see that the size (height) of the first letter (drop cap) is calculated by summing the height of the first and second lines.

hard to answer the question when you change it later

Xojo basically exposes two font attributes (that you care about)… TextHeight and TextAscent
TextHeight is from the top of the font cell (not the top of a character) to the bottom of the text cell, while TextAscender is the distance from the baseline to the bottom of the text cell.

Thanks for your feedback David. For now I did this like that way:

[code]Rects() As REALbasic.Rect

Sub Open()
Rects.Append(New REALbasic.Rect(100, 100, 150, 80))
Rects.Append(New REALbasic.Rect(100, Rects(0).Top + Rects(0).Height, 150, 50))
End Sub

Sub Paint(g As Graphics, areas() As REALbasic.Rect)
Dim i As Integer
Dim h As Integer = Rects(0).Height + rects(1).Height

g.TextFont = “Menlo”
Do Until g.TextAscent >= h * 1.3
g.TextSize = i
i = i + 1
Loop

For Each r As REALbasic.Rect In Rects
r.Left = g.StringWidth(“H”) + 25
g.DrawRect(r.Left, r.Top, r.Width, r.Height)
Next

g.DrawString(“H”, 25, Rects(0).Top + h)
End Sub[/code]

It does not work fine for all Fonts.

Yes, it will not because font properties are often specified by the font designer rather arbitrarily and pure Xojo does not reveal enough characteristics about fonts for a safe output.

If you look at the properties of NSFont, properties like boundingRectForFont would be those you are looking for.
If you dont want to use declares or plugins, you would possibly be on the safe side by analyzing the font in a graphics object for the relevant details. You would possibly want to cache the results as this operation could be quite time-consuming.

Speaking about speed: How about replacing this loop

``` Do Until g.TextAscent >= h * 1.3 g.TextSize = i i = i + 1 Loop```
by taking the TextAscent for a size like 100 and calculating the font size by use of the factor a division with the graphics height delivers?