A modern color science library for Kotlin Multiplatform and Java
3 min read
Color.kt
Color.kt is a modern color science library for Kotlin Multiplatform and Java. It includes modern perceptually-uniform color spaces and color appearance models, such as Oklab and ZCAM.
val oklab =Srgb("#9b392f").convert<Oklab>()
val lch = oklab.convert<Oklch>()
val boosted2 = lch.copy(C= lch.C*2).convert<Srgb>().toHex()
Advanced color appearance model usage
Model a color using ZCAM:
// Brightness of the displayval luminance =200.0// nits (cd/m²)// Conditions under which the color will be viewedval cond =Zcam.ViewingConditions(
surroundFactor =Zcam.ViewingConditions.SURROUND_AVERAGE,
adaptingLuminance =0.4* luminance,
// Mid-gray background at 50% luminance
backgroundLuminance =CieLab(50.0, 0.0, 0.0).toXyz().y * luminance,
// D65 is the only supported white point
referenceWhite =Illuminants.D65.toAbs(luminance),
)
// Color to convertval src =Srgb("#533b69")
// Use ZCAM to get perceptual color appearance attributesval zcam = src.toLinear().toXyz().toAbs(luminance).toZcam(cond)
Increase the chroma (colorfulness):
val colorful = zcam.copy(chroma = zcam.chroma *2)
Convert the color back to sRGB, while preserving hue and avoiding ugly results caused by hard clipping:
val srgb = colorful.clipToLinearSrgb()
Finally, print the new hex color code:
println(srgb.toHex())
Automatic conversion
Color.kt makes it easy to convert between any two color spaces by automatically finding the shortest path in the color conversion graph. This simplifies long conversions, which can occur frequently when working with different color spaces. For example, converting from CIELCh to Oklab LCh is usually done like this:
val oklab = cielch.toCieLab().toXyz().toLinearSrgb().toOklab().toOklch()
However, keep in mind that there is a performance cost associated with automatic conversion because it requires searching the graph. Conversion paths are cached after the first use, but it is still less efficient than manual conversion; prefer manual, explicit conversions in performance-critical code.
Custom color spaces
Color.kt includes several color spaces that should cover most use cases, but you can also add your own if necessary. Simply create a class that implements the Color interface, and implement some conversions to make the color space useful:
data classGrayColor(valbrightness:Double) : Color {
funtoLinearSrgb() =LinearSrgb(brightness, brightness, brightness)
companionobject {
// sRGB luminosity function from https://en.wikipedia.org/wiki/Relative_luminancefun LinearSrgb.toGray() =GrayColor(0.2126* r +0.7251* g +0.0722* b)
}
}
Optionally, add your new color space to the automatic conversion graph for convenient usage: