CaspianTerrazzo
CaspianTerrazzo

Reputation: 2148

How to load Fonts in Jetpack Compose Desktop?

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 file structure is different and I have no Access to R.font.my_font_400_regular since 'R' is an Android Resource feature.

Upvotes: 14

Views: 5909

Answers (4)

Mahozad
Mahozad

Reputation: 24532

This is for Compose Multiplatform v1.7.0.

  1. Add the resources dependency: implementation(compose.components.resources)
  2. Put the font files (ttf or otf) in src/commonMain/composeResources/font/
  3. Access the font with Res.font.font_name
    For example: val myFont = Font(Res.font.roboto)

For extended documentation, see the official docs.

Upvotes: 0

MisterAnt
MisterAnt

Reputation: 536

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
    )
)

Upvotes: 1

Alex Johnson
Alex Johnson

Reputation: 534

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.

Upvotes: 5

Saurabh Thorat
Saurabh Thorat

Reputation: 20674

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
    )
)

Upvotes: 26

Related Questions