Is there a way to center text when drawing using BmFont? I'm using the code from here: Using a BMP image as font in Monogame
The only code change I did was that I added a _TextWidth
int to DrawText
which uses DX - X
to get the text length, then a function GetTextLength
to return it to the button class, which then takes the ((button width - text width) / 2)
to get the starting point of the text, centering it. However, there seems to be some problems and the text doesn't center using its own text width, but using the next button's text width instead. Returning the text width is fine, but for some reason when it draws on-screen it's always the wrong values.
Added/changed code:
Public Sub DrawText(ByVal spritebatch As SpriteBatch, ByVal X As Integer, ByVal Y As Integer, ByVal Text As String)
Dim DX As Integer = X
Dim DY As Integer = Y
For Each C As Char In Text
Dim FC As New FontChar
If _CharacterMap.TryGetValue(C, FC) Then
Dim sourceRectangle = New Rectangle(FC.X, FC.Y, FC.Width, FC.Height)
Dim position = New Vector2(DX + FC.XOffset, DY + FC.YOffset)
spritebatch.Draw(_Texture, position, sourceRectangle, Color.White)
DX += FC.XAdvance
End If
Next
_TextWidth = DX - X
End Sub
Public Function GetTextLength() As Integer
Return _TextWidth
End Function
Screenshot:
Uncentered text, which could be centered if the right values were used for each button