Android Code Snippet [B4X] CreateB4XFont

Function to create custom B4XFont for all platforms.

I don't know if it is the best possible nor if it works perfectly with B4I, as I cannot test it, therefore suggestions/improvements will certainly be welcome.

B4XPages test project attached.

B4X:
'NativeFontSize is needed only for B4J or B4I.
'Of course you have to pass a dummy-not-used value if you are developing in B4A.
'It uses XUI (also FX in B4J) which must be declared at module level.
Public Sub CreateB4XFont(FontFileName As String, FontSize As Float, NativeFontSize As Float) As B4XFont
    #IF B4A
        Return xui.CreateFont(Typeface.LoadFromAssets(FontFileName), FontSize)
    #ELSE IF B4I
        Return xui.CreateFont(Font.CreateNew2(FontFileName, NativeFontSize), FontSize)
    #ELSE ' B4J
        Return xui.CreateFont(FX.LoadFont(File.DirAssets, FontFileName, NativeFontSize), FontSize)
    #END IF
End Sub
 

Attachments

  • CreateB4XFontTest.zip
    59.1 KB · Views: 267
Last edited:

TILogistic

Expert
Licensed User
Longtime User
Good "news", so you can download a font file and use it, at runtime.
The bad news is... why did you make me struggle when you could have published the snippet? πŸ˜„
I couldn't comment before, because I was watching the football of milan vs lazio.
πŸ˜‚πŸ˜‚πŸ˜‚πŸ˜‚
sorry.
 

Lucas Siqueira

Active Member
Licensed User
Longtime User
Small tweak for b4i.
Before trying to load the new font, it checks to see if it is added, avoiding a crash by loading the default font instead.

B4X:
Public Sub CreateB4XFont(FontFileName As String, FontSize As Float) As B4XFont
    #IF B4A
        Return xui.CreateFont(Typeface.LoadFromAssets(FontFileName), FontSize)
    #ELSE IF B4I
   
        FontFileName = FontFileName.Replace(".ttf","").Replace(".otf","")
       
        Dim existFont As Boolean = False
       
        For Each fontename As String In Font.AvailableNames
            If fontename = FontFileName Then
                existFont = True
                Exit
            End If
        Next
       
        If existFont Then
        Return xui.CreateFont(Font.CreateNew2(FontFileName, FontSize), FontSize)
        Else
            Log($"not found FontFileName: ${FontFileName}"$)
        Return xui.CreateDefaultFont(FontSize)
        End If
       
    #ELSE ' B4J
    Dim FX As JFX
    Return xui.CreateFont(FX.LoadFont(File.DirAssets, FontFileName, FontSize), FontSize)
    #END IF
End Sub


Remembering that in the b4i, it is necessary to add in the main module:
#AppFont: NameFonte.ttf
as Erel warns: https://www.b4x.com/android/forum/threads/custom-fonts.46461/


If you cannot find the correct name of the font, use this code to find out what the name of the font is, rename the file to the name found, to avoid an error in b4a with b4i: https://www.b4x.com/android/forum/threads/customfont-problem.65538/post-415157

B4X:
For Each s As String In Font.AvailableNames
 Log(s)
Next
 
Top