How to load Fonts in Jetpack Compose Desktop?
Asked Answered
N

3

14

In Jetpack Compose for android you can do this:


val fontFamily = FontFamily(
    Font(
        resId = R.font.my_font_400_regular,
        weight = FontWeight.W400,
        style = FontStyle.Normal
    ),
    Font(
        resId = R.font.my_font_400_italic,
        weight = FontWeight.W400,
        style = FontStyle.Italic
    )
)


But for Desktop the Filestructure is different and I have no Access to R.font.my_font_400_regular since 'R' is a Android Resource feature.

Northeast answered 9/3, 2021 at 12:15 Comment(0)
I
25

Put your .ttf font file in the src > main > resources folder. And then use:

val fontFamily = FontFamily(
    Font(
        resource = "font.ttf",
        weight = FontWeight.W400,
        style = FontStyle.Normal
    )
)
Injured answered 9/3, 2021 at 14:5 Comment(2)
The Font here is androidx.compose.ui.text.platform.FontLazes
Interesting fact: for some reason font files other than .ttf will not work. I spend some time trying to make it work with .otf font files, but to no avail. So just keep this in mind. .ttf onlyAerodonetics
K
5

Also, if you are using multiple fonts and want them to each be in their own sub-directory in resources like

resources/fonts/example1/

then make sure to include that directory in your 'resource' string in the Font creation.

Font(
    resource = "fonts/example1/examplefont_bold.ttf",
    weight = FontWeight.Bold,
    style = FontStyle.Normal
)

Probably obvious, but just in case.

Klein answered 28/4, 2022 at 13:36 Comment(0)
O
1

Other sample

val LatoFontFamily = FontFamily(
    Font(resource = "Fonts/Lato-Light.ttf", weight = FontWeight.Light),
    Font(resource = "Fonts/Lato-Regular.ttf", weight = FontWeight.Normal),
    Font(resource = "Fonts/Lato-Bold.ttf", weight = FontWeight.Bold)
)

val LatoFontBoldFamily = FontFamily(
    Font(resource = "Fonts/Lato-Bold.ttf", weight = FontWeight.Bold)
)

val typography = Typography(
    defaultFontFamily = LatoFontFamily,
    h1 = TextStyle(
        fontWeight = FontWeight.Light,
        fontSize = 96.sp,
        letterSpacing = (-1.5).sp
    ),
    h2 = TextStyle(
        fontWeight = FontWeight.Light,
        fontSize = 60.sp,
        letterSpacing = (-0.5).sp
    )
)
Orris answered 8/8, 2023 at 14:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.