Created
July 17, 2018 13:18
-
-
Save carlosefonseca/311dd81bf4b49d06968a80f9f91592d8 to your computer and use it in GitHub Desktop.
Easy way to manipulate an Android ColorInt as HSV and return the result as a ColorInt
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 android.graphics.Color | |
import android.support.annotation.ColorInt | |
import android.support.v4.graphics.ColorUtils | |
/** | |
* Convert the ARGB color to its HSV components. | |
*/ | |
class HSVColor(@ColorInt color: Int) { | |
val hsv = FloatArray(3).apply { Color.colorToHSV(color, this) } | |
inline var h | |
get() = hsv[HUE] | |
set(value) { | |
hsv[HUE] = value % 360 | |
} | |
inline var s | |
get() = hsv[SAT] | |
set(value) { | |
hsv[SAT] = value.coerceIn(0f, 1f) | |
} | |
inline var v | |
get() = hsv[VAL] | |
set(value) { | |
hsv[VAL] = value.coerceIn(0f, 1f) | |
} | |
var a = Color.alpha(color) | |
/** Converts the current HSV to a Color. */ | |
@ColorInt | |
inline fun color(): Int = ColorUtils.setAlphaComponent(Color.HSVToColor(hsv), a) | |
companion object { | |
const val HUE = 0 | |
const val SAT = 1 | |
const val VAL = 2 | |
} | |
} | |
/** | |
* Manipulate a color as HSV values. | |
* Example: | |
* ``` | |
* Color.RED.hsv { h += 50; s *= 0.5; v = 0.25 } | |
* ``` | |
*/ | |
@ColorInt | |
inline fun Int.hsv(block: HSVColor.() -> Unit): Int = HSVColor(this).apply(block).color() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment