Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load custom font with typesafe css?

Tags:

css

tornadofx

I want to load a custom font in a tornadofx-app with typesafe css, is this possible? Thanks and best regards.

like image 611
thlinde Avatar asked Mar 10 '23 17:03

thlinde


1 Answers

As long as a font is loaded, it can be used in CSS, so we've added a loadFont helper in TornadoFX that can be used like so:

class FontTest : App(Main::class, Styles::class)

class Main : View("Font Test") {
    override val root = stackpane {
        label("This is my Label") {
            addClass(Styles.custom)
        }
    }
}

class Styles : Stylesheet() {
    companion object {
        val custom by cssclass()
        // Note that loadFont() returns Font?
        val riesling = loadFont("/fonts/riesling.ttf", 48.0)
    }

    init {
        custom {
            padding = box(25.px)
            riesling?.let { font = it }
            // or if you just want to set the font family:
            // riesling?.let { fontFamily = it.family }
        }
    }
}

enter image description here

If you know for sure the font exists (e.g. you're including in your build), that can be simplified to:

class Styles : Stylesheet() {
    companion object {
        val custom by cssclass()
        val riesling = loadFont("/fonts/riesling.ttf", 48.0)!!
    }
    
    init {
        custom {
            padding = box(25.px)

            font = riesling
            // or if you just want to set the font family:
            // fontFamily = riesling.family
        }
    }
}
like image 97
Ruckus T-Boom Avatar answered Mar 30 '23 17:03

Ruckus T-Boom