https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
e

edenman

05/11/2020, 7:44 PM
Anybody else doing expect/actual abstraction over color values? I’m trying to have a shared color palette between my apps but getting a compiler NPE when i reference UIColor constants: https://youtrack.jetbrains.com/issue/KT-38850
s

saket

05/11/2020, 8:02 PM
Interesting. I’m sharing my colors as integers and wrapping it with NSColor() at usage sites so haven’t run into this yet.
e

edenman

05/11/2020, 8:17 PM
looks like i can get around it by just specifying the colors by calling the actual UIColor constructor for now
o

Omar Mainegra

05/12/2020, 2:57 PM
What I do: common
Copy code
expect class Color

expect fun fromRGB(r: Int, g: Int, b: Int): Color
expect fun fromARGB(a: Int, r: Int, g: Int, b: Int): Color
android
Copy code
actual typealias Color = Int

actual fun fromRGB(r: Int, g: Int, b: Int): Color = fromARGB(255, r, g, b)
actual fun fromARGB(a: Int, r: Int, g: Int, b: Int): Color = a shl 24 or (r shl 16) or (g shl 8) or b
iOS
Copy code
@Suppress("CONFLICTING_OVERLOADS") actual typealias Color = UIColor

actual fun fromRGB(r: Int, g: Int, b: Int) = UIColor(red = r / 255.0, green = g / 255.0, blue = b / 255.0, alpha = 1.0)
actual fun fromARGB(a: Int, r: Int, g: Int, b: Int) = UIColor(red = r / 255.0, green = g / 255.0, blue = b / 255.0, alpha = a / 255.0)
JS
Copy code
actual typealias Color = String

fun toHex(number: Int) =
    if (number >= 16) number.toString(16)
    else "0${number.toString(16)}"

actual fun fromRGB(r: Int, g: Int, b: Int): Color =
    "#${toHex(r)}${toHex(g)}${toHex(b)}".toUpperCase()

actual fun fromARGB(a: Int, r: Int, g: Int, b: Int): Color =
    "#${toHex(a)}${toHex(r)}${toHex(g)}${toHex(b)}".toUpperCase()
🙏🏼 1
e

edenman

05/12/2020, 6:16 PM
nice
o

Omar Mainegra

05/12/2020, 6:51 PM
Indeed, we have test cases in every platform to validate it
👍 1
2 Views