Created
August 8, 2025 00:31
-
-
Save FrancescoJo/b4aba11a81466f88d1979ea5c0422288 to your computer and use it in GitHub Desktop.
Various colour related Kotlin functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import kotlin.math.max | |
| import kotlin.math.min | |
| /** | |
| * @returns hue, saturation%, brightness% | |
| */ | |
| fun rgbToHsb(r: Int, g: Int, b: Int): Triple<Float, Float, Float> { | |
| val rF = r / 255f | |
| val gF = g / 255f | |
| val bF = b / 255f | |
| val cMax = max(max(rF, gF), bF) | |
| val cMin = min(min(rF, gF), bF) | |
| val delta = cMax - cMin | |
| val hue = when { | |
| delta == 0f -> 0f | |
| cMax == rF -> ((gF - bF) / delta) % 6 | |
| cMax == gF -> ((bF - rF) / delta) + 2 | |
| else -> ((rF - gF) / delta) + 4 | |
| } * 60 | |
| val saturation = if (cMax == 0f) { | |
| 0f | |
| } else { | |
| delta / cMax | |
| } | |
| val brightness = cMax | |
| return Triple( | |
| if (hue < 0) hue + 360 else hue, | |
| saturation * 100, | |
| brightness * 100 | |
| ) | |
| } | |
| fun isPrimaryColor(r: Int, g: Int, b: Int, threshold: Int = 30): Boolean { | |
| val isRed = r > 255 - threshold && g < threshold && b < threshold | |
| val isGreen = r < threshold && g > 255 - threshold && b < threshold | |
| val isBlue = r < threshold && g < threshold && b > 255 - threshold | |
| val isYellow = r > 255 - threshold && g > 255 - threshold && b < threshold | |
| return isRed || isGreen || isBlue || isYellow | |
| } | |
| fun isNeonColor(r: Int, g: Int, b: Int): Boolean { | |
| val (_, saturation, value) = rgbToHsv(r, g, b) | |
| // Definition of neon colour: over 85% saturation, 80% brightness | |
| val isHighSaturation = saturation > 85 | |
| val isHighValue = value > 80 | |
| return isHighSaturation && isHighValue | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment