11

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.

Johann
  • 27,536
  • 39
  • 165
  • 279
Luxusproblem
  • 1,913
  • 11
  • 23

3 Answers3

17

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
    )
)
Saurabh Thorat
  • 18,131
  • 5
  • 53
  • 70
  • 8
    The Font here is androidx.compose.ui.text.platform.Font – nima Jun 23 '21 at 15:34
  • 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` only – Pstr Jun 10 '22 at 15:32
4

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.

Alex Johnson
  • 504
  • 5
  • 15
0

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
    )
)
MisterAnt
  • 173
  • 8