From bee216aa3dcfd4d60efe0bdd3354a2514e2c8951 Mon Sep 17 00:00:00 2001 From: "Md. Touhidur Rahman" <46617994+touhidurrr@users.noreply.github.com> Date: Tue, 15 Jul 2025 14:51:49 +0600 Subject: [PATCH] Color: Better methods of brightening and darkening colors (#13611) * better brighten and darken * fix not returning new color * update method descriptions --- .../components/extensions/Scene2dExtensions.kt | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/core/src/com/unciv/ui/components/extensions/Scene2dExtensions.kt b/core/src/com/unciv/ui/components/extensions/Scene2dExtensions.kt index 4c154729bb..880d445dfe 100644 --- a/core/src/com/unciv/ui/components/extensions/Scene2dExtensions.kt +++ b/core/src/com/unciv/ui/components/extensions/Scene2dExtensions.kt @@ -42,6 +42,7 @@ import com.unciv.ui.components.input.onChange import com.unciv.ui.images.IconCircleGroup import com.unciv.ui.images.ImageGetter import com.unciv.ui.screens.basescreen.BaseScreen +import kotlin.math.max /** * Collection of extension functions mostly for libGdx widgets @@ -93,12 +94,16 @@ fun colorFromHex(hexColor: Int): Color { fun colorFromRGB(r: Int, g: Int, b: Int) = Color(r / 255f, g / 255f, b / 255f, 1f) /** Create a new [Color] instance from r/g/b given as Integers in the range 0..255 in the form of a 3-element List [rgb] */ fun colorFromRGB(rgb: List) = colorFromRGB(rgb[0], rgb[1], rgb[2]) -/** Linearly interpolates between this [Color] and [BLACK][ImageGetter.CHARCOAL] by [t] which is in the range [[0,1]]. - * The result is returned as a new instance. */ -fun Color.darken(t: Float): Color = Color(this).lerp(Color.BLACK, t) -/** Linearly interpolates between this [Color] and [WHITE][Color.WHITE] by [t] which is in the range [[0,1]]. - * The result is returned as a new instance. */ -fun Color.brighten(t: Float): Color = Color(this).lerp(Color.WHITE, t) +/** Linearly interpolates between this [Color] and [BLACK][ImageGetter.CHARCOAL] by [t] which is in the range [[0,1]], + * preserving color ratio in RGB. The result is returned as a new instance. */ +fun Color.darken(t: Float): Color = Color(this).mul(t) +/** Linearly interpolates between this [Color] and [WHITE][Color.WHITE] by [t] which is in the range [[0,1]], + * preserving color ratio in RGB. The result is returned as a new instance. */ +fun Color.brighten(t: Float): Color = Color(this).let { + val lightness = max(r, max(g, b)) + val targetRatio = (lightness + t * (1 - lightness)) / lightness + return it.mul(targetRatio) +} fun Actor.centerX(parent: Actor) { x = parent.width / 2 - width / 2 }