Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 850
Luxusproblem Avatar asked Mar 09 '21 12:03

Luxusproblem


People also ask

How do I change font size in compose?

To change font size of Text composable in Android Jetpack Compose, pass a required font size value for the optional fontSize parameter of Text composable. Make sure to import sp , as shown in the above code snippet, when you are assign fontSize property with scale-independent pixels.

What is textfield in jetpack compose?

TextField in Jetpack Compose What's TextField? TextField is a user interface control that is used to allow the user to enter the text. This widget is used to get the data from the user as numbers or text. A simple example of TextField is Login page. We get the username and password using TextField widget. What are options available in TextField?

What is materialtheme in jetpack?

A Material Theme defines the styling principles from the Material Design specification. In Jetpack Compose, MaterialTheme is available as a composable function with which we can customize the default attributes.

What is compose for desktop?

Compose for Desktop simplifies and accelerates UI development for desktop applications, and allows extensive UI code sharing between Android and desktop applications. Compose for Desktop provides a declarative and reactive approach to creating user interfaces with Kotlin.


2 Answers

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
    )
)
like image 87
Saurabh Thorat Avatar answered Oct 23 '22 11:10

Saurabh Thorat


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.

like image 3
Alex Johnson Avatar answered Oct 23 '22 12:10

Alex Johnson