Using L* creates a link between the color system, contrast, and thus accessibility. Contrast 26 | * ratio depends on relative luminance, or Y in the XYZ color space. L*, or perceptual luminance can 27 | * be calculated from Y. 28 | * 29 | *
Unlike Y, L* is linear to human perception, allowing trivial creation of accurate color tones. 30 | * 31 | *
Unlike contrast ratio, measuring contrast in L* is linear, and simple to calculate. A
32 | * difference of 40 in HCT tone guarantees a contrast ratio >= 3.0, and a difference of 50
33 | * guarantees a contrast ratio >= 4.5.
34 | */
35 |
36 |
37 | /**
38 | * HCT, hue, chroma, and tone. A color system that provides a perceptually accurate color
39 | * measurement system that can also accurately render what colors will appear as in different
40 | * lighting environments.
41 | */
42 | public final class Hct {
43 | private double hue;
44 | private double chroma;
45 | private double tone;
46 | private int argb;
47 |
48 | /**
49 | * Create an HCT color from hue, chroma, and tone.
50 | *
51 | * @param hue 0 <= hue < 360; invalid values are corrected.
52 | * @param chroma 0 <= chroma < ?; Informally, colorfulness. The color returned may be lower than
53 | * the requested chroma. Chroma has a different maximum for any given hue and tone.
54 | * @param tone 0 <= tone <= 100; invalid values are corrected.
55 | * @return HCT representation of a color in default viewing conditions.
56 | */
57 | public static Hct from(double hue, double chroma, double tone) {
58 | int argb = CamSolver.solveToInt(hue, chroma, tone);
59 | return new Hct(argb);
60 | }
61 |
62 | /**
63 | * Create an HCT color from a color.
64 | *
65 | * @param argb ARGB representation of a color.
66 | * @return HCT representation of a color in default viewing conditions
67 | */
68 | public static Hct fromInt(int argb) {
69 | return new Hct(argb);
70 | }
71 |
72 | private Hct(int argb) {
73 | setInternalState(argb);
74 | }
75 |
76 | public double getHue() {
77 | return hue;
78 | }
79 |
80 | public double getChroma() {
81 | return chroma;
82 | }
83 |
84 | public double getTone() {
85 | return tone;
86 | }
87 |
88 | public int toInt() {
89 | return argb;
90 | }
91 |
92 | /**
93 | * Set the hue of this color. Chroma may decrease because chroma has a different maximum for any
94 | * given hue and tone.
95 | *
96 | * @param newHue 0 <= newHue < 360; invalid values are corrected.
97 | */
98 | public void setHue(double newHue) {
99 | setInternalState(CamSolver.solveToInt(newHue, chroma, tone));
100 | }
101 |
102 | /**
103 | * Set the chroma of this color. Chroma may decrease because chroma has a different maximum for
104 | * any given hue and tone.
105 | *
106 | * @param newChroma 0 <= newChroma < ?
107 | */
108 | public void setChroma(double newChroma) {
109 | setInternalState(CamSolver.solveToInt(hue, newChroma, tone));
110 | }
111 |
112 | /**
113 | * Set the tone of this color. Chroma may decrease because chroma has a different maximum for any
114 | * given hue and tone.
115 | *
116 | * @param newTone 0 <= newTone <= 100; invalid valids are corrected.
117 | */
118 | public void setTone(double newTone) {
119 | setInternalState(CamSolver.solveToInt(hue, chroma, newTone));
120 | }
121 |
122 | private void setInternalState(int argb) {
123 | this.argb = argb;
124 | Cam16 cam = Cam16.fromInt(argb);
125 | hue = cam.getHue();
126 | chroma = cam.getChroma();
127 | this.tone = ColorUtils.lstarFromArgb(argb);
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/app/src/main/java/com/smarttoolfactory/composecolorsextended/demo/GradientAngleDemo.kt:
--------------------------------------------------------------------------------
1 | package com.smarttoolfactory.composecolorsextended.demo
2 |
3 | import androidx.compose.foundation.Canvas
4 | import androidx.compose.foundation.layout.*
5 | import androidx.compose.material.Slider
6 | import androidx.compose.material.Text
7 | import androidx.compose.runtime.*
8 | import androidx.compose.ui.Alignment
9 | import androidx.compose.ui.Modifier
10 | import androidx.compose.ui.graphics.Brush
11 | import androidx.compose.ui.graphics.Color
12 | import androidx.compose.ui.graphics.drawscope.DrawScope
13 | import androidx.compose.ui.text.font.FontWeight
14 | import androidx.compose.ui.unit.dp
15 | import androidx.compose.ui.unit.sp
16 | import com.smarttoolfactory.extendedcolors.GradientAngle
17 | import com.smarttoolfactory.extendedcolors.GradientOffset
18 | import com.smarttoolfactory.extendedcolors.MaterialColor.Blue400
19 | import kotlin.math.roundToInt
20 |
21 | /**
22 | * Demo for creating gradients for different type of pickers or sliders
23 | */
24 | @Composable
25 | fun GradientAngleDemo() {
26 |
27 | val canvasModifier = Modifier.size(300.dp)
28 |
29 | // Offsets for gradients based on selected angle
30 | var gradientOffset by remember {
31 | mutableStateOf(GradientOffset(GradientAngle.CW0))
32 | }
33 |
34 | var angleSelection by remember { mutableStateOf(0f) }
35 | var angleText by remember { mutableStateOf("0 Degrees") }
36 |
37 |
38 |
39 | Column(
40 | modifier = Modifier
41 | .fillMaxSize()
42 | .padding(8.dp),
43 | horizontalAlignment = Alignment.CenterHorizontally
44 | ) {
45 |
46 | Text(
47 | text = angleText,
48 | color = Blue400,
49 | modifier = Modifier
50 | .padding(8.dp),
51 | fontSize = 18.sp,
52 | fontWeight = FontWeight.Bold
53 | )
54 |
55 | Slider(
56 | modifier = Modifier.height(50.dp),
57 | value = angleSelection,
58 | onValueChange = {
59 | angleSelection = it
60 |
61 | gradientOffset = when (angleSelection.roundToInt()) {
62 | 0 -> {
63 | angleText = "0 Degrees"
64 | GradientOffset(GradientAngle.CW0)
65 | }
66 | 1 -> {
67 | angleText = "45 Degrees"
68 | GradientOffset(GradientAngle.CW45)
69 | }
70 | 2 -> {
71 | angleText = "90 Degrees"
72 | GradientOffset(GradientAngle.CW90)
73 | }
74 | 3 -> {
75 | angleText = "135 Degrees"
76 | GradientOffset(GradientAngle.CW135)
77 | }
78 | 4 -> {
79 | angleText = "180 Degrees"
80 | GradientOffset(GradientAngle.CW180)
81 | }
82 |
83 | 5 -> {
84 | angleText = "225 Degrees"
85 | GradientOffset(GradientAngle.CW225)
86 | }
87 | 6 -> {
88 | angleText = "270 Degrees"
89 | GradientOffset(GradientAngle.CW270)
90 | }
91 | else -> {
92 | angleText = "315 Degrees"
93 | GradientOffset(GradientAngle.CW315)
94 | }
95 | }
96 | },
97 | steps = 6,
98 | valueRange = 0f..7f
99 | )
100 |
101 | CanvasWithTitle(
102 | modifier = canvasModifier,
103 | text = "Gradient Angle"
104 | ) {
105 | val redGreenGradient = Brush.linearGradient(
106 | colors = listOf(Color.Red, Color.Green, Color.Blue),
107 | start = gradientOffset.start,
108 | end = gradientOffset.end
109 | )
110 | drawRect(redGreenGradient)
111 | }
112 |
113 | }
114 | }
115 |
116 | @Composable
117 | private fun CanvasWithTitle(
118 | modifier: Modifier = Modifier,
119 | text: String,
120 | onDraw: DrawScope.() -> Unit
121 | ) {
122 | Column(
123 | modifier = Modifier
124 | .wrapContentWidth()
125 | ) {
126 |
127 | Text(
128 | text = text,
129 | color = Blue400,
130 | modifier = Modifier
131 | .padding(8.dp),
132 | fontSize = 18.sp,
133 | fontWeight = FontWeight.Bold
134 | )
135 |
136 | Canvas(modifier = modifier, onDraw = onDraw)
137 | }
138 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/smarttoolfactory/composecolorsextended/M2ListColorPicker.kt:
--------------------------------------------------------------------------------
1 | package com.smarttoolfactory.composecolorsextended
2 |
3 | import androidx.compose.foundation.background
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.layout.*
6 | import androidx.compose.foundation.lazy.LazyColumn
7 | import androidx.compose.foundation.lazy.itemsIndexed
8 | import androidx.compose.foundation.shape.CircleShape
9 | import androidx.compose.foundation.shape.RoundedCornerShape
10 | import androidx.compose.material.Divider
11 | import androidx.compose.material.Text
12 | import androidx.compose.runtime.*
13 | import androidx.compose.ui.Alignment
14 | import androidx.compose.ui.Modifier
15 | import androidx.compose.ui.draw.clip
16 | import androidx.compose.ui.draw.shadow
17 | import androidx.compose.ui.graphics.Color
18 | import androidx.compose.ui.graphics.graphicsLayer
19 | import androidx.compose.ui.text.font.FontWeight
20 | import androidx.compose.ui.unit.dp
21 | import androidx.compose.ui.unit.sp
22 | import com.smarttoolfactory.extendedcolors.ColorSwatch
23 | import com.smarttoolfactory.extendedcolors.util.ColorUtil
24 |
25 | @Composable
26 | fun M2ListColorPicker(onColorChange: (Color) -> Unit) {
27 |
28 | var headerIndex by remember { mutableStateOf(0) }
29 | var selectedColorIndex by remember { mutableStateOf(-1) }
30 |
31 | Row(modifier = Modifier.fillMaxSize()) {
32 | LazyColumn(
33 | verticalArrangement = Arrangement.spacedBy(8.dp),
34 | contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp)
35 | ) {
36 | itemsIndexed(ColorSwatch.primaryHeaderColors) { index: Int, item: Color ->
37 | ColorDisplay(
38 | modifier = Modifier
39 | .padding(horizontal = 2.dp)
40 | .clip(CircleShape)
41 | .size(60.dp)
42 | .clickable {
43 | headerIndex = index
44 | }, color = item
45 | )
46 | }
47 | }
48 |
49 | val colorSwatch: LinkedHashMap For example, white under the traditional assumption of a midday sun white point is accurately
29 | * measured as a slightly chromatic blue by CAM16. (roughly, hue 203, chroma 3, lightness 100)
30 | *
31 | * This class caches intermediate values of the CAM16 conversion process that depend only on
32 | * viewing conditions, enabling speed ups.
33 | */
34 | public final class ViewingConditions {
35 | /** sRGB-like viewing conditions. */
36 | public static final ViewingConditions DEFAULT =
37 | ViewingConditions.make(
38 | new double[] {
39 | ColorUtils.whitePointD65()[0],
40 | ColorUtils.whitePointD65()[1],
41 | ColorUtils.whitePointD65()[2]
42 | },
43 | (200.0 / Math.PI * ColorUtils.yFromLstar(50.0) / 100.f),
44 | 50.0,
45 | 2.0,
46 | false);
47 |
48 | private final double aw;
49 | private final double nbb;
50 | private final double ncb;
51 | private final double c;
52 | private final double nc;
53 | private final double n;
54 | private final double[] rgbD;
55 | private final double fl;
56 | private final double flRoot;
57 | private final double z;
58 |
59 | public double getAw() {
60 | return aw;
61 | }
62 |
63 | public double getN() {
64 | return n;
65 | }
66 |
67 | public double getNbb() {
68 | return nbb;
69 | }
70 |
71 | double getNcb() {
72 | return ncb;
73 | }
74 |
75 | double getC() {
76 | return c;
77 | }
78 |
79 | double getNc() {
80 | return nc;
81 | }
82 |
83 | public double[] getRgbD() {
84 | return rgbD;
85 | }
86 |
87 | double getFl() {
88 | return fl;
89 | }
90 |
91 | public double getFlRoot() {
92 | return flRoot;
93 | }
94 |
95 | double getZ() {
96 | return z;
97 | }
98 |
99 | /**
100 | * Create ViewingConditions from a simple, physically relevant, set of parameters.
101 | *
102 | * @param whitePoint White point, measured in the XYZ color space. default = D65, or sunny day
103 | * afternoon
104 | * @param adaptingLuminance The luminance of the adapting field. Informally, how bright it is in
105 | * the room where the color is viewed. Can be calculated from lux by multiplying lux by
106 | * 0.0586. default = 11.72, or 200 lux.
107 | * @param backgroundLstar The lightness of the area surrounding the color. measured by L* in
108 | * L*a*b*. default = 50.0
109 | * @param surround A general description of the lighting surrounding the color. 0 is pitch dark,
110 | * like watching a movie in a theater. 1.0 is a dimly light room, like watching TV at home at
111 | * night. 2.0 means there is no difference between the lighting on the color and around it.
112 | * default = 2.0
113 | * @param discountingIlluminant Whether the eye accounts for the tint of the ambient lighting,
114 | * such as knowing an apple is still red in green light. default = false, the eye does not
115 | * perform this process on self-luminous objects like displays.
116 | */
117 | static ViewingConditions make(
118 | double[] whitePoint,
119 | double adaptingLuminance,
120 | double backgroundLstar,
121 | double surround,
122 | boolean discountingIlluminant) {
123 | // Transform white point XYZ to 'cone'/'rgb' responses
124 | double[][] matrix = Cam16.XYZ_TO_CAM16RGB;
125 | double[] xyz = whitePoint;
126 | double rW = (xyz[0] * matrix[0][0]) + (xyz[1] * matrix[0][1]) + (xyz[2] * matrix[0][2]);
127 | double gW = (xyz[0] * matrix[1][0]) + (xyz[1] * matrix[1][1]) + (xyz[2] * matrix[1][2]);
128 | double bW = (xyz[0] * matrix[2][0]) + (xyz[1] * matrix[2][1]) + (xyz[2] * matrix[2][2]);
129 | double f = 0.8 + (surround / 10.0);
130 | double c =
131 | (f >= 0.9)
132 | ? MathUtils.lerp(0.59, 0.69, ((f - 0.9) * 10.0))
133 | : MathUtils.lerp(0.525, 0.59, ((f - 0.8) * 10.0));
134 | double d =
135 | discountingIlluminant
136 | ? 1.0
137 | : f * (1.0 - ((1.0 / 3.6) * Math.exp((-adaptingLuminance - 42.0) / 92.0)));
138 | d = MathUtils.clampDouble(0.0, 1.0, d);
139 | double nc = f;
140 | double[] rgbD =
141 | new double[] {
142 | d * (100.0 / rW) + 1.0 - d, d * (100.0 / gW) + 1.0 - d, d * (100.0 / bW) + 1.0 - d
143 | };
144 | double k = 1.0 / (5.0 * adaptingLuminance + 1.0);
145 | double k4 = k * k * k * k;
146 | double k4F = 1.0 - k4;
147 | double fl = (k4 * adaptingLuminance) + (0.1 * k4F * k4F * Math.cbrt(5.0 * adaptingLuminance));
148 | double n = (ColorUtils.yFromLstar(backgroundLstar) / whitePoint[1]);
149 | double z = 1.48 + Math.sqrt(n);
150 | double nbb = 0.725 / Math.pow(n, 0.2);
151 | double ncb = nbb;
152 | double[] rgbAFactors =
153 | new double[] {
154 | Math.pow(fl * rgbD[0] * rW / 100.0, 0.42),
155 | Math.pow(fl * rgbD[1] * gW / 100.0, 0.42),
156 | Math.pow(fl * rgbD[2] * bW / 100.0, 0.42)
157 | };
158 |
159 | double[] rgbA =
160 | new double[] {
161 | (400.0 * rgbAFactors[0]) / (rgbAFactors[0] + 27.13),
162 | (400.0 * rgbAFactors[1]) / (rgbAFactors[1] + 27.13),
163 | (400.0 * rgbAFactors[2]) / (rgbAFactors[2] + 27.13)
164 | };
165 |
166 | double aw = ((2.0 * rgbA[0]) + rgbA[1] + (0.05 * rgbA[2])) * nbb;
167 | return new ViewingConditions(n, aw, nbb, ncb, c, nc, rgbD, fl, Math.pow(fl, 0.25), z);
168 | }
169 |
170 | /**
171 | * Parameters are intermediate values of the CAM16 conversion process. Their names are shorthand
172 | * for technical color science terminology, this class would not benefit from documenting them
173 | * individually. A brief overview is available in the CAM16 specification, and a complete overview
174 | * requires a color science textbook, such as Fairchild's Color Appearance Models.
175 | */
176 | private ViewingConditions(
177 | double n,
178 | double aw,
179 | double nbb,
180 | double ncb,
181 | double c,
182 | double nc,
183 | double[] rgbD,
184 | double fl,
185 | double flRoot,
186 | double z) {
187 | this.n = n;
188 | this.aw = aw;
189 | this.nbb = nbb;
190 | this.ncb = ncb;
191 | this.c = c;
192 | this.nc = nc;
193 | this.rgbD = rgbD;
194 | this.fl = fl;
195 | this.flRoot = flRoot;
196 | this.z = z;
197 | }
198 | }
199 |
--------------------------------------------------------------------------------
/extendedcolors/src/main/java/com/smarttoolfactory/extendedcolors/util/HSVUtil.kt:
--------------------------------------------------------------------------------
1 | package com.smarttoolfactory.extendedcolors.util
2 |
3 | import androidx.compose.ui.graphics.Color
4 | import com.smarttoolfactory.extendedcolors.util.ColorUtil.colorIntToRGBArray
5 |
6 |
7 | object HSVUtil {
8 | /*
9 | HSV-HSL Conversions
10 | */
11 | /**
12 | * Convert [HSV](https://en.wikipedia.org/wiki/HSL_and_HSV)
13 | * components(hue-saturation-value) to HSL
14 | * (hue-saturation-lightness) components.
15 | *
16 | * @param hue in [0..360f]
17 | * @param saturation in [0..1f]
18 | * @param value in [0..1f]
19 | * @return float array that contains hue, saturation and lightness
20 | */
21 | fun hsvToHSL(
22 | hue: Float,
23 | saturation: Float,
24 | value: Float
25 | ): FloatArray {
26 | val lightness = (2 - saturation) * value / 2
27 | var saturationHSL = saturation
28 |
29 | if (lightness != 0f) {
30 | saturationHSL = when {
31 | lightness == 1f -> {
32 | 0f
33 | }
34 | lightness < 0.5f -> {
35 | saturationHSL * value / (lightness * 2)
36 | }
37 | else -> {
38 | saturationHSL * value / (2 - lightness * 2)
39 | }
40 | }
41 | }
42 |
43 | return floatArrayOf(hue, saturationHSL.coerceIn(0f, 1f), lightness.coerceIn(0f, 1f))
44 | }
45 |
46 | /**
47 | * Convert [HSV](https://en.wikipedia.org/wiki/HSL_and_HSV)
48 | * components(hue-saturation-value) to HSL
49 | * (hue-saturation-lightness) components and apply them to [hslOut].
50 | * @param hue in [0..360f]
51 | * @param saturation in [0..1f]
52 | * @param value in [0..1f]
53 | * @param hslOut array contains hue, saturation and lightness properties
54 | *
55 | */
56 | fun hsvToHSL(
57 | hue: Float,
58 | saturation: Float,
59 | value: Float,
60 | hslOut: FloatArray
61 | ) {
62 | val lightness = (2 - saturation) * value / 2
63 | var saturationHSL = saturation
64 |
65 | if (lightness != 0f) {
66 | saturationHSL = when {
67 | lightness == 1f -> {
68 | 0f
69 | }
70 | lightness < 0.5f -> {
71 | saturationHSL * value / (lightness * 2)
72 | }
73 | else -> {
74 | saturationHSL * value / (2 - lightness * 2)
75 | }
76 | }
77 | }
78 |
79 | hslOut[0] = hue
80 | hslOut[1] = saturationHSL.coerceIn(0f, 1f)
81 | hslOut[2] = lightness.coerceIn(0f, 1f)
82 | }
83 |
84 | /**
85 | * Convert HSV components(hue-saturation-value) to HSL
86 | * (hue-saturation-lightness) components.
87 | *
88 | * ```
89 | * hsv[0] is Hue [0 .. 360)
90 | * hsv[1] is Saturation [0...1]
91 | * hsv[2] is Value [0...1]
92 | * ```
93 | * ```
94 | * hsl[0] is Hue [0 .. 360)
95 | * hsl[1] is Saturation [0...1]
96 | * hsl[2] is Lightness [0...1]
97 | * ```
98 | */
99 | fun hsvToHSL(hsvIn: FloatArray): FloatArray {
100 | return hsvToHSL(hsvIn[0], hsvIn[1], hsvIn[2])
101 | }
102 |
103 | /**
104 | * Convert HSV components(hue-saturation-value) to HSL
105 | * (hue-saturation-lightness) components.
106 | *
107 | * ```
108 | * hsv[0] is Hue [0 .. 360)
109 | * hsv[1] is Saturation [0...1]
110 | * hsv[2] is Value [0...1]
111 | * ```
112 | * ```
113 | * hsl[0] is Hue [0 .. 360)
114 | * hsl[1] is Saturation [0...1]
115 | * hsl[2] is Lightness [0...1]
116 | * ```
117 | */
118 | fun hsvToHSL(hsvIn: FloatArray, hslOut: FloatArray) {
119 | hsvToHSL(hsvIn[0], hsvIn[1], hsvIn[2], hslOut)
120 | }
121 |
122 |
123 | /*
124 | HSV-ColorInt Conversions
125 | */
126 |
127 | /**
128 | * Convert HSV (hue-saturation-value) components to a RGB color in [Integer] format.
129 | *
130 | * * For instance, red =255, green =0, blue=0 is -65536
131 | * @param hue in [0..360f]
132 | * @param saturation in [0..1f]
133 | * @param value in [0..1f]
134 | */
135 | fun hsvToColorInt(
136 | hue: Float,
137 | saturation: Float,
138 | value: Float
139 | ): Int {
140 | return hsvToColorInt(floatArrayOf(hue, saturation, value))
141 | }
142 |
143 |
144 | /**
145 | * Convert HSV (hue-saturation-value) components to a RGB color in [Integer] form.
146 | *
147 | * * For instance, red =255, green =0, blue=0 is -65536
148 | * ```
149 | * hsv[0] is Hue [0 .. 360)
150 | * hsv[1] is Saturation [0...1]
151 | * hsv[2] is Value [0...1]
152 | * ```
153 | * @param hsvIn 3 element array which holds the input HSV components.
154 | */
155 | fun hsvToColorInt(hsvIn: FloatArray): Int {
156 | return android.graphics.Color.HSVToColor(hsvIn)
157 | }
158 |
159 |
160 | /*
161 | HSV-Color Conversions
162 | */
163 |
164 | /**
165 | * Convert HSV (hue-saturation-value) components to Jetpack Compose [Color].
166 | * @param hue in [0..360f]
167 | * @param saturation in [0..1f]
168 | * @param value in [0..1f]
169 | * @param alpha in [0..1f]
170 | */
171 | fun hsvToColor(
172 | hue: Float,
173 | saturation: Float,
174 | value: Float,
175 | alpha: Float
176 | ): Color {
177 | return Color.hsv(hue, saturation, value, alpha)
178 | }
179 |
180 |
181 | /*
182 | HSV-RGB Conversions
183 | */
184 |
185 | /**
186 | * Convert HSV (hue-saturation-value) components to a RGB red, green blue array.
187 | * ```
188 | * rgb[0] is Red [0 .. 255]
189 | * rgb[1] is Green [0...255]
190 | * rgb[2] is Blue [0...255]
191 | * ```
192 | * @param hue in [0..360f]
193 | * @param saturation in [0..1f]
194 | * @param value in [0..1f]
195 | */
196 | fun hsvToRGB(
197 | hue: Float,
198 | saturation: Float,
199 | value: Float
200 | ): IntArray {
201 | return colorIntToRGBArray(
202 | hsvToColorInt(hue, saturation, value)
203 | )
204 | }
205 |
206 | /**
207 | * Convert HSV (hue-saturation-value) components to a RGB red, green blue array.
208 | * ```
209 | * hsv[0] is Hue [0 .. 360)
210 | * hsv[1] is Saturation [0...1]
211 | * hsv[2] is Value [0...1]
212 | * ```
213 | * ```
214 | * rgb[0] is Red [0 .. 255]
215 | * rgb[1] is Green [0...255]
216 | * rgb[2] is Blue [0...255]
217 | * ```
218 | * @param hsvIn 3 element array which holds the input HSV components.
219 | */
220 | fun hsvToRGB(hsvIn: FloatArray): IntArray {
221 | return colorIntToRGBArray(
222 | hsvToColorInt(hsvIn)
223 | )
224 | }
225 |
226 | /**
227 | * Convert HSV (hue-saturation-value) components to a RGB red, green blue array.
228 | * ```
229 | * rgb[0] is Red [0 .. 255]
230 | * rgb[1] is Green [0...255]
231 | * rgb[2] is Blue [0...255]
232 | * ```
233 | * @param hue in [0..360f]
234 | * @param saturation in [0..1f]
235 | * @param value in [0..1f]
236 | * @param rgbIn 3 element array which holds the input RGB components.
237 | */
238 | fun hsvToRGB(
239 | hue: Float,
240 | saturation: Float,
241 | value: Float,
242 | rgbIn: IntArray
243 | ) {
244 | colorIntToRGBArray(
245 | color = hsvToColorInt(hue, saturation, value),
246 | rgbIn = rgbIn
247 | )
248 | }
249 |
250 | /**
251 | * Convert HSV (hue-saturation-value) to RGB red, green, blue components in [0f..1f] range.
252 | * ```
253 | * rgb[0] is Red [0f .. 1f)
254 | * rgb[1] is Green [0f...1f]
255 | * rgb[2] is Blue [0f...1f]
256 | * ```
257 | * @param hue in [0..360f]
258 | * @param saturation in [0..1f]
259 | * @param value in [0..1f]
260 | *
261 | * @return 3 element array which holds the output RGB components.
262 | */
263 | fun hsvToRGBFloat(
264 | hue: Float,
265 | saturation: Float,
266 | value: Float
267 | ): FloatArray {
268 | val color = Color.hsv(hue, saturation, value)
269 | return floatArrayOf(color.red, color.green, color.blue)
270 | }
271 |
272 | /**
273 | * Convert HSV (hue-saturation-value) to RGB red, green, blue components in [0f..1f] range.
274 | * ```
275 | * rgb[0] is Red [0f .. 1f)
276 | * rgb[1] is Green [0f...1f]
277 | * rgb[2] is Blue [0f...1f]
278 | * ```
279 | * @param hue in [0..360f]
280 | * @param saturation in [0..1f]
281 | * @param value in [0..1f]
282 | * @param rgbIn 3 element array which holds the output RGB components.
283 | */
284 | fun hsvToRGBFloat(
285 | hue: Float,
286 | saturation: Float,
287 | value: Float,
288 | rgbIn: FloatArray
289 | ) {
290 | val color = Color.hsv(hue, saturation, value)
291 | rgbIn[0] = color.red
292 | rgbIn[1] = color.green
293 | rgbIn[2] = color.blue
294 | }
295 |
296 | }
--------------------------------------------------------------------------------
/extendedcolors/src/main/java/com/smarttoolfactory/extendedcolors/util/ColorUtil.kt:
--------------------------------------------------------------------------------
1 | package com.smarttoolfactory.extendedcolors.util
2 |
3 | import androidx.compose.ui.graphics.Color
4 | import androidx.compose.ui.graphics.toArgb
5 | import androidx.core.graphics.ColorUtils
6 | import com.smarttoolfactory.extendedcolors.util.RGBUtil.argbToHex
7 | import com.smarttoolfactory.extendedcolors.util.RGBUtil.rgbToHSL
8 | import com.smarttoolfactory.extendedcolors.util.RGBUtil.rgbToHSV
9 | import com.smarttoolfactory.extendedcolors.util.RGBUtil.rgbToHex
10 |
11 |
12 | object ColorUtil {
13 |
14 | /**
15 | * Convert Jetpack Compose [Color] to HSV (hue-saturation-value) components.
16 | * ```
17 | * Hue is [0 .. 360)
18 | * Saturation is [0...1]
19 | * Value is [0...1]
20 | * ```
21 | * @param hslIn 3 element array which holds the input HSL components.
22 | */
23 | fun colorToHSV(color: Color, hslIn: FloatArray) {
24 | val rgbArray: IntArray = colorIntToRGBArray(color.toArgb())
25 | val red = rgbArray[0]
26 | val green = rgbArray[1]
27 | val blue = rgbArray[2]
28 | rgbToHSV(red, green, blue, hslIn)
29 | }
30 |
31 | /**
32 | * Convert Jetpack Compose [Color] to HSV (hue-saturation-value) components.
33 | * ```
34 | * Hue is [0 .. 360)
35 | * Saturation is [0...1]
36 | * Value is [0...1]
37 | * ```
38 | */
39 | fun colorToHSV(color: Color): FloatArray {
40 | val rgbArray: IntArray = colorIntToRGBArray(color.toArgb())
41 | val red = rgbArray[0]
42 | val green = rgbArray[1]
43 | val blue = rgbArray[2]
44 | return rgbToHSV(red, green, blue)
45 | }
46 |
47 | /**
48 | * Convert Jetpack Compose [Color] to HSV (hue-saturation-value) components.
49 | * ```
50 | * hsl[0] is Hue [0 .. 360)
51 | * hsl[1] is Saturation [0...1]
52 | * hsl[2] is Lightness [0...1]
53 | * ```
54 | * @param hslIn 3 element array which holds the input HSL components.
55 | */
56 | fun colorToHSL(color: Color, hslIn: FloatArray) {
57 | val rgbArray: IntArray = colorIntToRGBArray(color.toArgb())
58 | val red = rgbArray[0]
59 | val green = rgbArray[1]
60 | val blue = rgbArray[2]
61 | rgbToHSL(red, green, blue, hslIn)
62 | }
63 |
64 | /**
65 | * Convert Jetpack Compose [Color] to HSV (hue-saturation-value) components.
66 | * ```
67 | * hsl[0] is Hue [0 .. 360)
68 | * hsl[1] is Saturation [0...1]
69 | * hsl[2] is Lightness [0...1]
70 | * ```
71 | */
72 | fun colorToHSL(color: Color): FloatArray {
73 | val rgbArray: IntArray = colorIntToRGBArray(color.toArgb())
74 | val red = rgbArray[0]
75 | val green = rgbArray[1]
76 | val blue = rgbArray[2]
77 | return rgbToHSL(red, green, blue)
78 | }
79 |
80 | /*
81 | COLOR-RGB Conversions
82 | */
83 |
84 | /**
85 | * Convert Jetpack [Color] into 3 element array of red, green, and blue
86 | *```
87 | * rgb[0] is Red [0 .. 255]
88 | * rgb[1] is Green [0...255]
89 | * rgb[2] is Blue [0...255]
90 | * ```
91 | * @param color Jetpack Compose [Color]
92 | * @return 3 element array which holds the input RGB components.
93 | */
94 | fun colorToARGBArray(color: Color): IntArray {
95 | return colorIntToRGBArray(color.toArgb())
96 | }
97 |
98 | /**
99 | * Convert Jetpack [Color] into 3 element array of red, green, and blue
100 | *```
101 | * rgb[0] is Red [0 .. 255]
102 | * rgb[1] is Green [0...255]
103 | * rgb[2] is Blue [0...255]
104 | * ```
105 | * @param color Jetpack Compose [Color]
106 | * @return 3 element array which holds the input RGB components.
107 | */
108 | fun colorToRGBArray(color: Color): IntArray {
109 | return colorIntToRGBArray(color.toArgb())
110 | }
111 |
112 | /**
113 | * Convert Jetpack [Color] into 3 element array of red, green, and blue
114 | *```
115 | * rgb[0] is Red [0 .. 255]
116 | * rgb[1] is Green [0...255]
117 | * rgb[2] is Blue [0...255]
118 | * ```
119 | * @param color Jetpack Compose [Color]
120 | * @param rgbIn 3 element array which holds the input RGB components.
121 | */
122 | fun colorToRGBArray(color: Color, rgbIn: IntArray) {
123 | val argbArray = colorIntToRGBArray(color.toArgb())
124 | rgbIn[0] = argbArray[0]
125 | rgbIn[1] = argbArray[1]
126 | rgbIn[2] = argbArray[2]
127 | }
128 |
129 |
130 | fun colorToHex(color: Color): String {
131 | return rgbToHex(color.red, color.green, color.blue)
132 | }
133 |
134 | fun colorToHexAlpha(color: Color): String {
135 | return argbToHex(color.alpha, color.red, color.green, color.blue)
136 | }
137 |
138 | /**
139 | * Convert a RGB color in [Integer] form to HSV (hue-saturation-value) components.
140 | * * For instance, red =255, green =0, blue=0 is -65536
141 | * ```
142 | * hsv[0] is Hue [0 .. 360)
143 | * hsv[1] is Saturation [0...1]
144 | * hsv[2] is Value [0...1]
145 | * ```
146 | */
147 | fun colorIntToHSV(color: Int): FloatArray {
148 | val hsvOut = floatArrayOf(0f, 0f, 0f)
149 | android.graphics.Color.colorToHSV(color, hsvOut)
150 | return hsvOut
151 | }
152 |
153 | /**
154 | * Convert a RGB color in [Integer] form to HSV (hue-saturation-value) components.
155 | * * For instance, red =255, green =0, blue=0 is -65536
156 | *
157 | * ```
158 | * hsv[0] is Hue [0 .. 360)
159 | * hsv[1] is Saturation [0...1]
160 | * hsv[2] is Value [0...1]
161 | * ```
162 | * @param hsvIn 3 element array which holds the input HSV components.
163 | */
164 | fun colorIntToHSV(color: Int, hsvIn: FloatArray) {
165 | android.graphics.Color.colorToHSV(color, hsvIn)
166 | }
167 |
168 |
169 | /**
170 | * Convert RGB color [Integer] to HSL (hue-saturation-lightness) components.
171 | * ```
172 | * hsl[0] is Hue [0 .. 360)
173 | * hsl[1] is Saturation [0...1]
174 | * hsl[2] is Lightness [0...1]
175 | * ```
176 | */
177 | fun colorIntToHSL(color: Int): FloatArray {
178 | val hslOut = floatArrayOf(0f, 0f, 0f)
179 | ColorUtils.colorToHSL(color, hslOut)
180 | return hslOut
181 | }
182 |
183 | /**
184 | * Convert RGB color [Integer] to HSL (hue-saturation-lightness) components.
185 | * ```
186 | * hsl[0] is Hue [0 .. 360)
187 | * hsl[1] is Saturation [0...1]
188 | * hsl[2] is Lightness [0...1]
189 | * ```
190 | */
191 | fun colorIntToHSL(color: Int, hslIn: FloatArray) {
192 | ColorUtils.colorToHSL(color, hslIn)
193 | }
194 |
195 |
196 | /*
197 | ColorInt-RGB Conversions
198 | */
199 | /**
200 | * Convert Color [Integer] into 3 element array of red, green, and blue
201 | *```
202 | * rgb[0] is Red [0 .. 255]
203 | * rgb[1] is Green [0...255]
204 | * rgb[2] is Blue [0...255]
205 | * ```
206 | * @return 3 element array which holds the input RGB components.
207 | */
208 | fun colorIntToRGBArray(color: Int): IntArray {
209 | val red = android.graphics.Color.red(color)
210 | val green = android.graphics.Color.green(color)
211 | val blue = android.graphics.Color.blue(color)
212 | return intArrayOf(red, green, blue)
213 | }
214 |
215 | /**
216 | * Convert Color [Integer] into 3 element array of red, green, and blue
217 | *```
218 | * rgb[0] is Red [0 .. 255]
219 | * rgb[1] is Green [0...255]
220 | * rgb[2] is Blue [0...255]
221 | * ```
222 | * @param rgbIn 3 element array which holds the input RGB components.
223 | */
224 | fun colorIntToRGBArray(color: Int, rgbIn: IntArray) {
225 | val red = android.graphics.Color.red(color)
226 | val green = android.graphics.Color.green(color)
227 | val blue = android.graphics.Color.blue(color)
228 |
229 | rgbIn[0] = red
230 | rgbIn[1] = green
231 | rgbIn[2] = blue
232 | }
233 |
234 | /**
235 | * Convert Color [Integer] into 4 element array of alpha red, green, and blue
236 | *```
237 | * rgb[0] is Alpha [0 .. 255]
238 | * rgb[1] is Red [0 .. 255]
239 | * rgb[2] is Green [0...255]
240 | * rgb[3] is Blue [0...255]
241 | * ```
242 | * @return 4 element array which holds the input ARGB components.
243 | */
244 | fun colorIntToARGBArray(color: Int): IntArray {
245 | val alpha = android.graphics.Color.alpha(color)
246 | val red = android.graphics.Color.red(color)
247 | val green = android.graphics.Color.green(color)
248 | val blue = android.graphics.Color.blue(color)
249 | return intArrayOf(alpha, red, green, blue)
250 | }
251 |
252 | /**
253 | * Convert Color [Integer] into 4 element array of alpha red, green, and blue
254 | *```
255 | * rgb[0] is Alpha [0 .. 255]
256 | * rgb[1] is Red [0 .. 255]
257 | * rgb[2] is Green [0...255]
258 | * rgb[3] is Blue [0...255]
259 | * ```
260 | * @param argbIn 4 element array which holds the input ARGB components.
261 | */
262 | fun colorIntToARGBArray(color: Int, argbIn: IntArray) {
263 | val alpha = android.graphics.Color.alpha(color)
264 | val red = android.graphics.Color.red(color)
265 | val green = android.graphics.Color.green(color)
266 | val blue = android.graphics.Color.blue(color)
267 |
268 | argbIn[0] = alpha
269 | argbIn[1] = red
270 | argbIn[2] = green
271 | argbIn[3] = blue
272 | }
273 | }
--------------------------------------------------------------------------------
/extendedcolors/src/main/java/com/smarttoolfactory/extendedcolors/md3/utils/ColorUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 Google LLC
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | // This file is automatically generated. Do not modify it.
18 |
19 | package com.smarttoolfactory.extendedcolors.md3.utils;
20 |
21 | /**
22 | * Color science utilities.
23 | *
24 | * Utility methods for color science constants and color space conversions that aren't HCT or
25 | * CAM16.
26 | */
27 | public class ColorUtils {
28 | private ColorUtils() {}
29 |
30 | static final double[][] SRGB_TO_XYZ =
31 | new double[][] {
32 | new double[] {0.41233895, 0.35762064, 0.18051042},
33 | new double[] {0.2126, 0.7152, 0.0722},
34 | new double[] {0.01932141, 0.11916382, 0.95034478},
35 | };
36 |
37 | static final double[][] XYZ_TO_SRGB =
38 | new double[][] {
39 | new double[] {
40 | 3.2413774792388685, -1.5376652402851851, -0.49885366846268053,
41 | },
42 | new double[] {
43 | -0.9691452513005321, 1.8758853451067872, 0.04156585616912061,
44 | },
45 | new double[] {
46 | 0.05562093689691305, -0.20395524564742123, 1.0571799111220335,
47 | },
48 | };
49 |
50 | static final double[] WHITE_POINT_D65 = new double[] {95.047, 100.0, 108.883};
51 |
52 | /** Converts a color from RGB components to ARGB format. */
53 | public static int argbFromRgb(int red, int green, int blue) {
54 | return (255 << 24) | ((red & 255) << 16) | ((green & 255) << 8) | (blue & 255);
55 | }
56 |
57 | /** Converts a color from linear RGB components to ARGB format. */
58 | public static int argbFromLinrgb(double[] linrgb) {
59 | int r = delinearized(linrgb[0]);
60 | int g = delinearized(linrgb[1]);
61 | int b = delinearized(linrgb[2]);
62 | return argbFromRgb(r, g, b);
63 | }
64 |
65 | /** Returns the alpha component of a color in ARGB format. */
66 | public static int alphaFromArgb(int argb) {
67 | return (argb >> 24) & 255;
68 | }
69 |
70 | /** Returns the red component of a color in ARGB format. */
71 | public static int redFromArgb(int argb) {
72 | return (argb >> 16) & 255;
73 | }
74 |
75 | /** Returns the green component of a color in ARGB format. */
76 | public static int greenFromArgb(int argb) {
77 | return (argb >> 8) & 255;
78 | }
79 |
80 | /** Returns the blue component of a color in ARGB format. */
81 | public static int blueFromArgb(int argb) {
82 | return argb & 255;
83 | }
84 |
85 | /** Returns whether a color in ARGB format is opaque. */
86 | public static boolean isOpaque(int argb) {
87 | return alphaFromArgb(argb) >= 255;
88 | }
89 |
90 | /** Converts a color from ARGB to XYZ. */
91 | public static int argbFromXyz(double x, double y, double z) {
92 | double[][] matrix = XYZ_TO_SRGB;
93 | double linearR = matrix[0][0] * x + matrix[0][1] * y + matrix[0][2] * z;
94 | double linearG = matrix[1][0] * x + matrix[1][1] * y + matrix[1][2] * z;
95 | double linearB = matrix[2][0] * x + matrix[2][1] * y + matrix[2][2] * z;
96 | int r = delinearized(linearR);
97 | int g = delinearized(linearG);
98 | int b = delinearized(linearB);
99 | return argbFromRgb(r, g, b);
100 | }
101 |
102 | /** Converts a color from XYZ to ARGB. */
103 | public static double[] xyzFromArgb(int argb) {
104 | double r = linearized(redFromArgb(argb));
105 | double g = linearized(greenFromArgb(argb));
106 | double b = linearized(blueFromArgb(argb));
107 | return MathUtils.matrixMultiply(new double[] {r, g, b}, SRGB_TO_XYZ);
108 | }
109 |
110 | /** Converts a color represented in Lab color space into an ARGB integer. */
111 | public static int argbFromLab(double l, double a, double b) {
112 | double[] whitePoint = WHITE_POINT_D65;
113 | double fy = (l + 16.0) / 116.0;
114 | double fx = a / 500.0 + fy;
115 | double fz = fy - b / 200.0;
116 | double xNormalized = labInvf(fx);
117 | double yNormalized = labInvf(fy);
118 | double zNormalized = labInvf(fz);
119 | double x = xNormalized * whitePoint[0];
120 | double y = yNormalized * whitePoint[1];
121 | double z = zNormalized * whitePoint[2];
122 | return argbFromXyz(x, y, z);
123 | }
124 |
125 | /**
126 | * Converts a color from ARGB representation to L*a*b* representation.
127 | *
128 | * @param argb the ARGB representation of a color
129 | * @return a Lab object representing the color
130 | */
131 | public static double[] labFromArgb(int argb) {
132 | double linearR = linearized(redFromArgb(argb));
133 | double linearG = linearized(greenFromArgb(argb));
134 | double linearB = linearized(blueFromArgb(argb));
135 | double[][] matrix = SRGB_TO_XYZ;
136 | double x = matrix[0][0] * linearR + matrix[0][1] * linearG + matrix[0][2] * linearB;
137 | double y = matrix[1][0] * linearR + matrix[1][1] * linearG + matrix[1][2] * linearB;
138 | double z = matrix[2][0] * linearR + matrix[2][1] * linearG + matrix[2][2] * linearB;
139 | double[] whitePoint = WHITE_POINT_D65;
140 | double xNormalized = x / whitePoint[0];
141 | double yNormalized = y / whitePoint[1];
142 | double zNormalized = z / whitePoint[2];
143 | double fx = labF(xNormalized);
144 | double fy = labF(yNormalized);
145 | double fz = labF(zNormalized);
146 | double l = 116.0 * fy - 16;
147 | double a = 500.0 * (fx - fy);
148 | double b = 200.0 * (fy - fz);
149 | return new double[] {l, a, b};
150 | }
151 |
152 | /**
153 | * Converts an L* value to an ARGB representation.
154 | *
155 | * @param lstar L* in L*a*b*
156 | * @return ARGB representation of grayscale color with lightness matching L*
157 | */
158 | public static int argbFromLstar(double lstar) {
159 | double fy = (lstar + 16.0) / 116.0;
160 | double fz = fy;
161 | double fx = fy;
162 | double kappa = 24389.0 / 27.0;
163 | double epsilon = 216.0 / 24389.0;
164 | boolean lExceedsEpsilonKappa = lstar > 8.0;
165 | double y = lExceedsEpsilonKappa ? fy * fy * fy : lstar / kappa;
166 | boolean cubeExceedEpsilon = fy * fy * fy > epsilon;
167 | double x = cubeExceedEpsilon ? fx * fx * fx : lstar / kappa;
168 | double z = cubeExceedEpsilon ? fz * fz * fz : lstar / kappa;
169 | double[] whitePoint = WHITE_POINT_D65;
170 | return argbFromXyz(x * whitePoint[0], y * whitePoint[1], z * whitePoint[2]);
171 | }
172 |
173 | /**
174 | * Computes the L* value of a color in ARGB representation.
175 | *
176 | * @param argb ARGB representation of a color
177 | * @return L*, from L*a*b*, coordinate of the color
178 | */
179 | public static double lstarFromArgb(int argb) {
180 | double y = xyzFromArgb(argb)[1] / 100.0;
181 | double e = 216.0 / 24389.0;
182 | if (y <= e) {
183 | return 24389.0 / 27.0 * y;
184 | } else {
185 | double yIntermediate = Math.pow(y, 1.0 / 3.0);
186 | return 116.0 * yIntermediate - 16.0;
187 | }
188 | }
189 |
190 | /**
191 | * Converts an L* value to a Y value.
192 | *
193 | * L* in L*a*b* and Y in XYZ measure the same quantity, luminance.
194 | *
195 | * L* measures perceptual luminance, a linear scale. Y in XYZ measures relative luminance, a
196 | * logarithmic scale.
197 | *
198 | * @param lstar L* in L*a*b*
199 | * @return Y in XYZ
200 | */
201 | public static double yFromLstar(double lstar) {
202 | double ke = 8.0;
203 | if (lstar > ke) {
204 | return Math.pow((lstar + 16.0) / 116.0, 3.0) * 100.0;
205 | } else {
206 | return lstar / (24389.0 / 27.0) * 100.0;
207 | }
208 | }
209 |
210 | /**
211 | * Linearizes an RGB component.
212 | *
213 | * @param rgbComponent 0 <= rgb_component <= 255, represents R/G/B channel
214 | * @return 0.0 <= output <= 100.0, color channel converted to linear RGB space
215 | */
216 | public static double linearized(int rgbComponent) {
217 | double normalized = rgbComponent / 255.0;
218 | if (normalized <= 0.040449936) {
219 | return normalized / 12.92 * 100.0;
220 | } else {
221 | return Math.pow((normalized + 0.055) / 1.055, 2.4) * 100.0;
222 | }
223 | }
224 |
225 | /**
226 | * Delinearizes an RGB component.
227 | *
228 | * @param rgbComponent 0.0 <= rgb_component <= 100.0, represents linear R/G/B channel
229 | * @return 0 <= output <= 255, color channel converted to regular RGB space
230 | */
231 | public static int delinearized(double rgbComponent) {
232 | double normalized = rgbComponent / 100.0;
233 | double delinearized = 0.0;
234 | if (normalized <= 0.0031308) {
235 | delinearized = normalized * 12.92;
236 | } else {
237 | delinearized = 1.055 * Math.pow(normalized, 1.0 / 2.4) - 0.055;
238 | }
239 | return MathUtils.clampInt(0, 255, (int) Math.round(delinearized * 255.0));
240 | }
241 |
242 | /**
243 | * Returns the standard white point; white on a sunny day.
244 | *
245 | * @return The white point
246 | */
247 | public static double[] whitePointD65() {
248 | return WHITE_POINT_D65;
249 | }
250 |
251 | static double labF(double t) {
252 | double e = 216.0 / 24389.0;
253 | double kappa = 24389.0 / 27.0;
254 | if (t > e) {
255 | return Math.pow(t, 1.0 / 3.0);
256 | } else {
257 | return (kappa * t + 16) / 116;
258 | }
259 | }
260 |
261 | static double labInvf(double ft) {
262 | double e = 216.0 / 24389.0;
263 | double kappa = 24389.0 / 27.0;
264 | double ft3 = ft * ft * ft;
265 | if (ft3 > e) {
266 | return ft3;
267 | } else {
268 | return (116 * ft - 16) / kappa;
269 | }
270 | }
271 |
272 | }
273 |
274 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2022 Smart Tool Factory
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/extendedcolors/src/main/java/com/smarttoolfactory/extendedcolors/util/RGBUtil.kt:
--------------------------------------------------------------------------------
1 | package com.smarttoolfactory.extendedcolors.util
2 |
3 | import androidx.core.graphics.ColorUtils
4 | import com.smarttoolfactory.extendedcolors.util.ColorUtil.colorIntToHSL
5 | import com.smarttoolfactory.extendedcolors.util.ColorUtil.colorIntToHSV
6 | import java.util.*
7 |
8 | object RGBUtil {
9 |
10 | /**
11 | * Convert RGB red, green blue to HSV (hue-saturation-value) components.
12 | * ```
13 | * hsv[0] is Hue [0 .. 360)
14 | * hsv[1] is Saturation [0...1]
15 | * hsv[2] is Value [0...1]
16 | * ```
17 | * @param red Red component [0..255] of the color
18 | * @param green Green component [0..255] of the color
19 | * @param blue Blue component [0..255] of the color
20 | */
21 | fun rgbToHSV(
22 | red: Int,
23 | green: Int,
24 | blue: Int
25 | ): FloatArray {
26 | val hsvOut = floatArrayOf(0f, 0f, 0f)
27 | android.graphics.Color.RGBToHSV(red, green, blue, hsvOut)
28 | return hsvOut
29 | }
30 |
31 | /**
32 | * Convert RGB red, green blue to HSV (hue-saturation-value) components.
33 | * ```
34 | * hsv[0] is Hue [0 .. 360)
35 | * hsv[1] is Saturation [0...1]
36 | * hsv[2] is Value [0...1]
37 | * ```
38 | * @param red Red component [0..255] of the color
39 | * @param green Green component [0..255] of the color
40 | * @param blue Blue component [0..255] of the color
41 | * @param hsvIn 3 element array which holds the output HSV components.
42 | */
43 | fun rgbToHSV(
44 | red: Int,
45 | green: Int,
46 | blue: Int,
47 | hsvIn: FloatArray
48 | ) {
49 | android.graphics.Color.RGBToHSV(red, green, blue, hsvIn)
50 | }
51 |
52 |
53 | /**
54 | * Convert RGB red, green blue to HSL (hue-saturation-lightness) components.
55 | * ```
56 | * hsl[0] is Hue [0 .. 360)
57 | * hsl[1] is Saturation [0...1]
58 | * hsl[2] is Lightness [0...1]
59 | * ```
60 | * @param red Red component [0..255] of the color
61 | * @param green Green component [0..255] of the color
62 | * @param blue Blue component [0..255] of the color
63 | */
64 | fun rgbToHSL(
65 | red: Int,
66 | green: Int,
67 | blue: Int
68 | ): FloatArray {
69 | val outHsl = floatArrayOf(0f, 0f, 0f)
70 | ColorUtils.RGBToHSL(red, green, blue, outHsl)
71 | return outHsl
72 | }
73 |
74 | /**
75 | * Convert RGB red, green blue to HSL (hue-saturation-lightness) components.
76 | * ```
77 | * hsl[0] is Hue [0 .. 360)
78 | * hsl[1] is Saturation [0...1]
79 | * hsl[2] is Lightness [0...1]
80 | * ```
81 | * @param red Red component [0..255] of the color
82 | * @param green Green component [0..255] of the color
83 | * @param blue Blue component [0..255] of the color
84 | * @param hslIn 3 element array which holds the input HSL components.
85 | */
86 | fun rgbToHSL(
87 | red: Int,
88 | green: Int,
89 | blue: Int,
90 | hslIn: FloatArray
91 | ) {
92 | ColorUtils.RGBToHSL(red, green, blue, hslIn)
93 | }
94 |
95 | /**
96 | * Convert RGB red, green, blue components in [0f..1f] range to
97 | * HSV (hue-saturation-value) components.
98 | *
99 | * @param red Red component [0..255] of the color
100 | * @param green Green component [0..255] of the color
101 | * @param blue Blue component [0..255] of the color
102 | * @return 3 element array which holds the output RGB components.
103 | */
104 | fun rgbFloatToHSV(
105 | red: Float,
106 | green: Float,
107 | blue: Float
108 | ): FloatArray {
109 | val colorInt = rgbToColorInt(red = red, green = green, blue = blue)
110 | val outHsl = floatArrayOf(0f, 0f, 0f)
111 | colorIntToHSV(colorInt, outHsl)
112 | return outHsl
113 | }
114 |
115 | /**
116 | * Convert RGB red, green, blue components in [0f..1f] range to
117 | * HSV (hue-saturation-value) components.
118 | *
119 | * @param red Red component [0..255] of the color
120 | * @param green Green component [0..255] of the color
121 | * @param blue Blue component [0..255] of the color
122 | * @param hsvIn 3 element array which holds the output HSV components.
123 | */
124 | fun rgbFloatToHSV(
125 | red: Float,
126 | green: Float,
127 | blue: Float,
128 | hsvIn: FloatArray
129 | ) {
130 | val colorInt = rgbToColorInt(red = red, green = green, blue = blue)
131 | colorIntToHSV(colorInt, hsvIn)
132 | }
133 |
134 |
135 | /**
136 | * Convert RGB red, green blue in [0f..1f] range to HSL (hue-saturation-lightness) components.
137 | * ```
138 | * hsl[0] is Hue [0 .. 360)
139 | * hsl[1] is Saturation [0...1]
140 | * hsl[2] is Lightness [0...1]
141 | * ```
142 | * @param red Red component [0f..1f] of the color
143 | * @param green Green component [0f..1f] of the color
144 | * @param blue Blue component [0f..1f] of the color
145 | */
146 | fun rgbFloatToHSL(
147 | red: Float,
148 | green: Float,
149 | blue: Float
150 | ): FloatArray {
151 | val colorInt = rgbToColorInt(red = red, green = green, blue = blue)
152 | val outHsl = floatArrayOf(0f, 0f, 0f)
153 | colorIntToHSL(colorInt, outHsl)
154 | return outHsl
155 | }
156 |
157 | /**
158 | * Convert RGB red, green blue in [0f..1f] range to HSL (hue-saturation-lightness) components.
159 | * ```
160 | * hsl[0] is Hue [0 .. 360)
161 | * hsl[1] is Saturation [0...1]
162 | * hsl[2] is Lightness [0...1]
163 | * ```
164 | * @param red Red component [0f..1f] of the color
165 | * @param green Green component [0f..1f] of the color
166 | * @param blue Blue component [0f..1f] of the color
167 | * @param hslIn 3 element array which holds the input HSL components.
168 | */
169 | fun rgbFloatToHSL(
170 | red: Float,
171 | green: Float,
172 | blue: Float,
173 | hslIn: FloatArray
174 | ) {
175 | val colorInt = rgbToColorInt(red = red, green = green, blue = blue)
176 | colorIntToHSL(colorInt, hslIn)
177 | }
178 |
179 |
180 | /**
181 | * Return a color-int from alpha, red, green, blue components.
182 | * These component values should be [0..255], but there is no range check performed,
183 | * so if they are out of range, the returned color is undefined.
184 | *
185 | * @param red Red component [0..255] of the color
186 | * @param green Green component [0..255] of the color
187 | * @param blue Blue component [0..255] of the color
188 | */
189 | fun rgbToColorInt(
190 | red: Int,
191 | green: Int,
192 | blue: Int
193 | ): Int {
194 | return android.graphics.Color.rgb(red, green, blue)
195 | }
196 |
197 | /**
198 | * Return a color-int from alpha, red, green, blue components.
199 | * These component values should be [0f..1f], but there is no range check performed,
200 | * so if they are out of range, the returned color is undefined.
201 | *
202 | * @param red Red component [0f..1f] of the color
203 | * @param green Green component [0..1f] of the color
204 | * @param blue Blue component [0..1f] of the color
205 | *
206 | */
207 | fun rgbToColorInt(
208 | red: Float,
209 | green: Float,
210 | blue: Float
211 | ): Int {
212 | val redInt = red.fractionToRGBRange()
213 | val greenInt = green.fractionToRGBRange()
214 | val blueInt = blue.fractionToRGBRange()
215 | return android.graphics.Color.rgb(redInt, greenInt, blueInt)
216 | }
217 |
218 |
219 | /**
220 | * Convert red, green, blue components [0..255] range in [Integer] to Hex format String
221 | */
222 | fun rgbToHex(
223 | red: Int,
224 | green: Int,
225 | blue: Int
226 | ): String {
227 | return "#" +
228 | Integer.toHexString(red).toStringComponent() +
229 | Integer.toHexString(green).toStringComponent() +
230 | Integer.toHexString(blue).toStringComponent()
231 | }
232 |
233 | /**
234 | * Convert rgb array to Hex format String
235 | * ```
236 | * rgb[0] is Red [0 .. 255]
237 | * rgb[1] is Green [0...255]
238 | * rgb[2] is Blue [0...255]
239 | * ```
240 | */
241 | fun rgbToHex(rgb: IntArray): String {
242 | return "#" +
243 | Integer.toHexString(rgb[0]).toStringComponent() +
244 | Integer.toHexString(rgb[1]).toStringComponent() +
245 | Integer.toHexString(rgb[2]).toStringComponent()
246 | }
247 |
248 | /**
249 | * Convert red, green, blue components [0f..1f] range in [Float] to Hex format String
250 | */
251 | fun rgbToHex(
252 | red: Float,
253 | green: Float,
254 | blue: Float
255 | ): String {
256 | return "#" +
257 | Integer.toHexString(red.fractionToRGBRange()).toStringComponent() +
258 | Integer.toHexString(green.fractionToRGBRange()).toStringComponent() +
259 | Integer.toHexString(blue.fractionToRGBRange()).toStringComponent()
260 | }
261 |
262 |
263 | /**
264 | * Return a color-int from alpha, red, green, blue components.
265 | * These component values should be [0..255], but there is no range check performed,
266 | * so if they are out of range, the returned color is undefined.
267 | *
268 | * @param alpha Alpha component [0..255] of the color
269 | * @param red Red component [0..255] of the color
270 | * @param green Green component [0..255] of the color
271 | * @param blue Blue component [0..255] of the color
272 | */
273 | fun argbToColorInt(
274 | alpha: Int,
275 | red: Int,
276 | green: Int,
277 | blue: Int
278 | ): Int {
279 | return android.graphics.Color.argb(alpha, red, green, blue)
280 | }
281 |
282 | /**
283 | * Return a color-int from alpha, red, green, blue components.
284 | * These component values should be [0f..1f], but there is no range check performed,
285 | * so if they are out of range, the returned color is undefined.
286 | *
287 | * @param alpha Alpha component [0f..1f] of the color
288 | * @param red Red component [0f..1f] of the color
289 | * @param green Green component [0..1f] of the color
290 | * @param blue Blue component [0..1f] of the color
291 | */
292 | fun argbToColorInt(
293 | alpha: Float,
294 | red: Float,
295 | green: Float,
296 | blue: Float
297 | ): Int {
298 | val alphaInt = alpha.fractionToRGBRange()
299 | val redInt = red.fractionToRGBRange()
300 | val greenInt = green.fractionToRGBRange()
301 | val blueInt = blue.fractionToRGBRange()
302 | return android.graphics.Color.argb(alphaInt, redInt, greenInt, blueInt)
303 | }
304 |
305 |
306 | /**
307 | * Convert alpha, red, green, blue components in [0..255] range argb to Hex format String
308 | *
309 | * ```
310 | * Alpha is [0 .. 255]
311 | * Red is [0 .. 255]
312 | * Green is [0...255]
313 | * Blue is [0...255]
314 | * ```
315 | */
316 | fun argbToHex(
317 | alpha: Int,
318 | red: Int,
319 | green: Int,
320 | blue: Int
321 | ): String {
322 | return "#" +
323 | Integer.toHexString(alpha).toStringComponent() +
324 | Integer.toHexString(red).toStringComponent() +
325 | Integer.toHexString(green).toStringComponent() +
326 | Integer.toHexString(blue).toStringComponent()
327 | }
328 |
329 | /**
330 | * Convert alpha, red, green, blue components in [0f..1f] range in [Float] argb to Hex format String
331 | *
332 | * ```
333 | * Alpha is [0f .. 1f]
334 | * Red is [0f .. 1f]
335 | * Green is [0...1f]
336 | * Blue is [0...1f]
337 | * ```
338 | */
339 | fun argbToHex(
340 | alpha: Float,
341 | red: Float,
342 | green: Float,
343 | blue: Float
344 | ): String {
345 | return "#" +
346 | Integer.toHexString(alpha.fractionToRGBRange()).toStringComponent() +
347 | Integer.toHexString(red.fractionToRGBRange()).toStringComponent() +
348 | Integer.toHexString(green.fractionToRGBRange()).toStringComponent() +
349 | Integer.toHexString(blue.fractionToRGBRange()).toStringComponent()
350 | }
351 |
352 | /*
353 | RGB-HEX Conversions
354 | */
355 | /**
356 | * Get hex representation of a rgb Color in [Integer] format
357 | */
358 | fun Int.toRgbString(): String =
359 | ("#" +
360 | red.toStringComponent() +
361 | green.toStringComponent() +
362 | blue.toStringComponent())
363 | .uppercase(Locale.getDefault())
364 |
365 | /**
366 | * Get hex representation of a argb Color in [Integer] format
367 | */
368 | fun Int.toArgbString(): String =
369 | ("#" +
370 | alpha.toStringComponent() +
371 | red.toStringComponent() +
372 | green.toStringComponent() +
373 | blue.toStringComponent()
374 | ).uppercase(Locale.getDefault())
375 |
376 | private fun String.toStringComponent() =
377 | this.let { if (it.length == 1) "0${it}" else it }
378 |
379 | private fun Int.toStringComponent(): String =
380 | this.toString(16).let { if (it.length == 1) "0${it}" else it }
381 |
382 | inline val Int.alpha: Int
383 | get() = (this shr 24) and 0xFF
384 |
385 | inline val Int.red: Int
386 | get() = (this shr 16) and 0xFF
387 |
388 | inline val Int.green: Int
389 | get() = (this shr 8) and 0xFF
390 |
391 | inline val Int.blue: Int
392 | get() = this and 0xFF
393 |
394 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/smarttoolfactory/composecolorsextended/demo/ColorModeConversionDemo.kt:
--------------------------------------------------------------------------------
1 | package com.smarttoolfactory.composecolorsextended.demo
2 |
3 | import androidx.compose.foundation.background
4 | import androidx.compose.foundation.layout.*
5 | import androidx.compose.foundation.rememberScrollState
6 | import androidx.compose.foundation.shape.RoundedCornerShape
7 | import androidx.compose.foundation.verticalScroll
8 | import androidx.compose.material.Slider
9 | import androidx.compose.material.Text
10 | import androidx.compose.runtime.*
11 | import androidx.compose.ui.Alignment
12 | import androidx.compose.ui.Modifier
13 | import androidx.compose.ui.draw.clip
14 | import androidx.compose.ui.draw.shadow
15 | import androidx.compose.ui.graphics.Color
16 | import androidx.compose.ui.graphics.toArgb
17 | import androidx.compose.ui.text.font.FontWeight
18 | import androidx.compose.ui.unit.dp
19 | import androidx.compose.ui.unit.sp
20 | import com.smarttoolfactory.extendedcolors.util.*
21 | import com.smarttoolfactory.extendedcolors.util.RGBUtil.toArgbString
22 |
23 |
24 | /**
25 | * Converting from HSV or HSL to RGB and then from RGB to HSV or HSL doesn't bear correct
26 | * results all the time. This demo displays when it doesn't work as exptected
27 | */
28 | @Composable
29 | fun ColorModelConversionDemo() {
30 |
31 | Column(
32 | modifier = Modifier
33 | .verticalScroll(rememberScrollState())
34 | .fillMaxSize()
35 | .background(Color.LightGray)
36 | .padding(vertical = 10.dp),
37 | horizontalAlignment = Alignment.CenterHorizontally
38 | ) {
39 |
40 | val modifier = Modifier
41 | .padding(8.dp)
42 | .shadow(2.dp, RoundedCornerShape(8.dp))
43 | .background(Color.White)
44 | .padding(4.dp)
45 |
46 | val sliderModifier = Modifier.padding(horizontal = 8.dp)
47 |
48 | val boxModifier = Modifier
49 | .padding(horizontal = 8.dp, vertical = 4.dp)
50 | .clip(RoundedCornerShape(8.dp))
51 | .fillMaxWidth(.8f)
52 | .height(40.dp)
53 |
54 |
55 | // Panels that contain 0 to 4 sliders based on which callback is implemented
56 | HSVSliderDisplayPanelExample(modifier, sliderModifier, boxModifier)
57 | HSLSliderDisplayPanelExample(modifier, sliderModifier, boxModifier)
58 | }
59 | }
60 |
61 | @Composable
62 | private fun HSVSliderDisplayPanelExample(
63 | modifier: Modifier,
64 | sliderModifier: Modifier,
65 | boxModifier: Modifier
66 | ) {
67 | var hue by remember { mutableStateOf(0f) }
68 | var saturation by remember { mutableStateOf(.5f) }
69 | var value by remember { mutableStateOf(.5f) }
70 | var alpha by remember { mutableStateOf(1f) }
71 |
72 | val colorHSV = Color.hsv(hue = hue, saturation = saturation, value = value, alpha = alpha)
73 |
74 | Title(
75 | text = "Conversions from HSV"
76 | )
77 |
78 | Column(
79 | modifier = modifier,
80 | horizontalAlignment = Alignment.CenterHorizontally
81 | ) {
82 |
83 | Box(modifier = boxModifier.background(colorHSV))
84 |
85 | CheckColorConversionDetailsFromHSV(
86 | color = colorHSV,
87 | hue = hue,
88 | saturation = saturation,
89 | value = value,
90 | alpha = alpha
91 | )
92 |
93 | Slider(modifier = sliderModifier, value = hue, onValueChange = { hue = it })
94 | Slider(modifier = sliderModifier, value = saturation, onValueChange = { saturation = it })
95 | Slider(modifier = sliderModifier, value = value, onValueChange = { value = it })
96 | Slider(modifier = sliderModifier, value = alpha, onValueChange = { alpha = it })
97 | }
98 | }
99 |
100 | @Composable
101 | private fun HSLSliderDisplayPanelExample(
102 | modifier: Modifier,
103 | sliderModifier: Modifier,
104 | boxModifier: Modifier
105 | ) {
106 |
107 | var hue by remember { mutableStateOf(0f) }
108 | var saturation by remember { mutableStateOf(.5f) }
109 | var lightness by remember { mutableStateOf(.5f) }
110 | var alpha by remember { mutableStateOf(1f) }
111 |
112 | val colorHSL =
113 | Color.hsl(hue = hue, saturation = saturation, lightness = lightness, alpha = alpha)
114 |
115 | Title(
116 | text = "Conversions from HSL"
117 | )
118 |
119 | Column(
120 | modifier = modifier,
121 | horizontalAlignment = Alignment.CenterHorizontally
122 | ) {
123 | Box(modifier = boxModifier.background(colorHSL))
124 |
125 | CheckColorConversionDetailsFromHSL(
126 | colorHSL,
127 | hue,
128 | saturation,
129 | lightness,
130 | alpha
131 | )
132 |
133 | Slider(modifier = sliderModifier, value = hue, onValueChange = { hue = it })
134 | Slider(modifier = sliderModifier, value = saturation, onValueChange = { saturation = it })
135 | Slider(modifier = sliderModifier, value = lightness, onValueChange = { lightness = it })
136 | Slider(modifier = sliderModifier, value = alpha, onValueChange = { alpha = it })
137 | }
138 | }
139 |
140 | @Composable
141 | private fun Title(text: String) {
142 | Text(
143 | text,
144 | color = Color.Red,
145 | fontWeight = FontWeight.Bold,
146 | fontSize = 18.sp,
147 | modifier = Modifier.padding(vertical = 12.dp)
148 | )
149 | }
150 |
151 | @Composable
152 | private fun CheckColorConversionDetailsFromHSV(
153 | color: Color,
154 | hue: Float,
155 | saturation: Float,
156 | value: Float,
157 | alpha: Float
158 | ) {
159 | val red = color.red.fractionToRGBRange()
160 | val green = color.green.fractionToRGBRange()
161 | val blue = color.blue.fractionToRGBRange()
162 |
163 |
164 | /*
165 | 🔥 Conversions
166 | */
167 |
168 | // Convert Color into ColorInt then to alpha, red, green, blue array
169 | val colorInt = color.toArgb()
170 | val argbArrayFromColor: IntArray = ColorUtil.colorIntToARGBArray(colorInt)
171 |
172 | // Convert to RGB from HSV
173 | val rgbArray = HSVUtil.hsvToRGB(hue = hue, saturation = saturation, value = value)
174 |
175 | // Convert to HSL from HSV
176 | val hslArrayFromHSV = HSVUtil.hsvToHSL(hue, saturation, value)
177 | val hueHslFromHSV = hslArrayFromHSV[0].toInt()
178 | val saturationHslFromHSV = hslArrayFromHSV[1].fractionToPercent()
179 | val lightnessHslFromHSV = hslArrayFromHSV[2].fractionToPercent()
180 |
181 | // Convert to HSL from Color's red, green, blue
182 | // 🔥 This conversion does not give correct result all the time
183 | val hslArrayFromRGB = RGBUtil.rgbToHSL(red, green, blue)
184 | val hueHslFromRGB = hslArrayFromRGB[0].toInt()
185 | val saturationHslFromRGB = hslArrayFromRGB[1].fractionToPercent()
186 | val lightnessHslFromRGB = hslArrayFromRGB[2].fractionToPercent()
187 |
188 | // Convert to HSV from Color's red, green, blue
189 | // 🔥 This conversion does not give correct result all the time
190 | val hsvArrayFromRGB = RGBUtil.rgbToHSV(red, green, blue)
191 | val hueHsvFromRGB = hsvArrayFromRGB[0].toInt()
192 | val saturationHsvFromRGB = hsvArrayFromRGB[1].fractionToPercent()
193 | val valueHsvFromRGB = hsvArrayFromRGB[2].fractionToPercent()
194 |
195 | Text(
196 | "RAW Hue: ${hue}\n" +
197 | "RAW sat $saturation\n" +
198 | "RAW lightness: $value\n" +
199 | "HEX: ${colorInt.toArgbString()}"
200 | )
201 |
202 | Text(
203 | "RGB from Color.toArgb()\n" +
204 | "alpha: ${argbArrayFromColor[0]}, " +
205 | "red: ${argbArrayFromColor[1]}, " +
206 | "green: ${argbArrayFromColor[2]}, " +
207 | "blue: ${argbArrayFromColor[3]}\n",
208 | )
209 |
210 | // RGB Result Comparison
211 | val isRGBColorsSame = (red != rgbArray[0] || green != rgbArray[1] || blue != rgbArray[2])
212 |
213 | Text(
214 | "RGB from Color\n" +
215 | "red: $red, green: $green, blue: $blue",
216 | color = if (isRGBColorsSame) Color.Red else Color.LightGray
217 | )
218 |
219 | Text(
220 | "RGB from HSV\n" +
221 | "red: ${rgbArray[0]}, green: ${rgbArray[1]}, blue: ${rgbArray[2]}\n",
222 | color = if (isRGBColorsSame) Color.Red else Color.LightGray
223 | )
224 |
225 | // 🔥 When RGB is Converted to HSV or HSL colors don't match with actual one
226 | // This applies to any color picker
227 | // colorpicker.me/ Check colors in this link
228 |
229 | // HSL Result Comparison
230 | val areHslColorsNotSame =
231 | (hueHslFromHSV != hueHslFromRGB ||
232 | saturationHslFromHSV != saturationHslFromRGB ||
233 | lightnessHslFromHSV != lightnessHslFromRGB
234 | )
235 |
236 | Text(
237 | "HSL from HSV Conversion\n" +
238 | "hue: $hueHslFromHSV, " +
239 | "sat: $saturationHslFromHSV, " +
240 | "light: $lightnessHslFromHSV",
241 | color = if (areHslColorsNotSame) Color.Red else Color.LightGray
242 | )
243 |
244 | Text(
245 | "HSL from RGB Conversion\n" +
246 | "hue: $hueHslFromRGB, " +
247 | "sat: $saturationHslFromRGB, " +
248 | "light: $lightnessHslFromRGB\n",
249 | color = if (areHslColorsNotSame) Color.Red else Color.LightGray
250 | )
251 |
252 | // HSV Result Comparison
253 | val hueRounded = hue.toInt()
254 | val saturationRounded = saturation.fractionToPercent()
255 | val valueRounded = value.fractionToPercent()
256 |
257 | val areHSVColorsSame = (hueRounded == hueHsvFromRGB &&
258 | saturationRounded == saturationHsvFromRGB &&
259 | valueRounded == valueHsvFromRGB
260 | )
261 |
262 | Text(
263 | "HSL RAW rounded\n" +
264 | "hue: $hueRounded, " +
265 | "sat: $saturationRounded, " +
266 | "value: $valueRounded",
267 | color = if (!areHSVColorsSame) Color.Red else Color.LightGray
268 | )
269 | Text(
270 | "HSL from RGB Conversion\n" +
271 | "hue: $hueHsvFromRGB, " +
272 | "sat: $saturationHsvFromRGB, " +
273 | "value: $valueHsvFromRGB",
274 | color = if (!areHSVColorsSame) Color.Red else Color.LightGray
275 | )
276 |
277 | }
278 |
279 |
280 | /**
281 | * This is an example for conversions from HSL to HSV, HSV to RGB and from RGB to HSV nd HSL
282 | *
283 | * 🔥 When RGB is Converted to HSV or HSL colors don't match with actual one
284 | * Check this online [color picker](colorpicker.me/) to cross-check results
285 | */
286 | @Composable
287 | private fun CheckColorConversionDetailsFromHSL(
288 | color: Color,
289 | hue: Float,
290 | saturation: Float,
291 | lightness: Float,
292 | alpha: Float
293 | ) {
294 |
295 | val red = color.red.fractionToRGBRange()
296 | val green = color.green.fractionToRGBRange()
297 | val blue = color.blue.fractionToRGBRange()
298 |
299 |
300 | /*
301 | 🔥 Conversions
302 | */
303 |
304 | // Convert Color into ColorInt then to alpha, red, green, blue array
305 | val colorInt = color.toArgb()
306 | val argbArrayFromColor: IntArray = ColorUtil.colorIntToARGBArray(colorInt)
307 |
308 | // Convert to RGB from HSL
309 | val rgbArray = HSLUtil.hslToRGB(hue = hue, saturation = saturation, lightness = lightness)
310 |
311 | // Convert to HSV from HSL
312 | val hsvArrayFromHSL = HSLUtil.hslToHSV(hue, saturation, lightness)
313 | val hueHsvFromHSL = hsvArrayFromHSL[0].toInt()
314 | val saturationHsvFromHSL = hsvArrayFromHSL[1].fractionToPercent()
315 | val valueHsvFromHSL = hsvArrayFromHSL[2].fractionToPercent()
316 |
317 | // Convert to HSV from Color's red, green, blue
318 | // 🔥 This conversion does not give correct result all the time
319 | val hsvArrayFromRGB = RGBUtil.rgbToHSV(red, green, blue)
320 | val hueHsvFromRGB = hsvArrayFromRGB[0].toInt()
321 | val saturationHsvFromRGB = hsvArrayFromRGB[1].fractionToPercent()
322 | val valueHsvFromRGB = hsvArrayFromRGB[2].fractionToPercent()
323 |
324 | // Convert to HSL from Color's red, green, blue
325 | // 🔥 This conversion does not give correct result all the time
326 | val hslArrayFromRGB = RGBUtil.rgbToHSL(red, green, blue)
327 | val hueHslFromRGB = hslArrayFromRGB[0].toInt()
328 | val saturationHslFromRGB = hslArrayFromRGB[1].fractionToPercent()
329 | val lightnessHslFromRGB = hslArrayFromRGB[2].fractionToPercent()
330 |
331 |
332 | Text(
333 | "RAW Hue: ${hue}\n" +
334 | "RAW sat $saturation\n" +
335 | "RAW lightness: $lightness\n" +
336 | "HEX: ${colorInt.toArgbString()}"
337 | )
338 |
339 | Text(
340 | "RGB from Color.toArgb()\n" +
341 | "alpha: ${argbArrayFromColor[0]}, " +
342 | "red: ${argbArrayFromColor[1]}, " +
343 | "green: ${argbArrayFromColor[2]}, " +
344 | "blue: ${argbArrayFromColor[3]}\n",
345 | )
346 |
347 | // RGB Result Comparison
348 | val areRGBColorsSame = (red != rgbArray[0] || green != rgbArray[1] || blue != rgbArray[2])
349 | Text(
350 | "RGB from Color\n" +
351 | "red: $red, green: $green, blue: $blue",
352 | color = if (areRGBColorsSame) Color.Red else Color.LightGray
353 | )
354 |
355 | Text(
356 | "RGB from HSL\n" +
357 | "red: ${rgbArray[0]}, green: ${rgbArray[1]}, blue: ${rgbArray[2]}\n",
358 | color = if (areRGBColorsSame) Color.Red else Color.LightGray
359 | )
360 |
361 | // HSV Result Comparison
362 | val areHsvColorsSame =
363 | (hueHsvFromHSL == hueHsvFromRGB &&
364 | saturationHsvFromHSL == saturationHsvFromRGB &&
365 | valueHsvFromHSL == valueHsvFromRGB)
366 |
367 | Text(
368 | "HSV from HSL Conversion\n" +
369 | "hue: $hueHsvFromHSL, " +
370 | "sat: $saturationHsvFromHSL, " +
371 | "value: $valueHsvFromHSL",
372 | color = if (!areHsvColorsSame) Color.Red else Color.LightGray
373 | )
374 |
375 | Text(
376 | "HSV from RGB Conversion\n" +
377 | "hue: $hueHsvFromRGB, " +
378 | "sat: $saturationHsvFromRGB, " +
379 | "value: $valueHsvFromRGB\n",
380 | color = if (!areHsvColorsSame) Color.Red else Color.LightGray
381 | )
382 |
383 | // HSL Result Comparison
384 | val hueRounded = hue.toInt()
385 | val saturationRounded = saturation.fractionToPercent()
386 | val lightnessRounded = lightness.fractionToPercent()
387 |
388 | val areHSLColorsSame = (hueRounded == hueHslFromRGB &&
389 | saturationRounded == saturationHslFromRGB &&
390 | lightnessRounded == lightnessHslFromRGB
391 | )
392 |
393 | Text(
394 | "HSL RAW rounded\n" +
395 | "hue: $hueRounded, " +
396 | "sat: $saturationRounded, " +
397 | "light: $lightnessRounded",
398 | color = if (!areHSLColorsSame) Color.Red else Color.LightGray
399 | )
400 | Text(
401 | "HSL from RGB Conversion\n" +
402 | "hue: $hueHslFromRGB, " +
403 | "sat: $saturationHslFromRGB, " +
404 | "light: $lightnessHslFromRGB",
405 | color = if (!areHSLColorsSame) Color.Red else Color.LightGray
406 | )
407 | }
408 |
409 |
--------------------------------------------------------------------------------
/app/src/main/java/com/smarttoolfactory/composecolorsextended/M3ColorPicker.kt:
--------------------------------------------------------------------------------
1 | package com.smarttoolfactory.composecolorsextended
2 |
3 | import android.content.Context
4 | import android.widget.Toast
5 | import androidx.compose.foundation.background
6 | import androidx.compose.foundation.clickable
7 | import androidx.compose.foundation.layout.*
8 | import androidx.compose.foundation.lazy.grid.GridCells
9 | import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
10 | import androidx.compose.foundation.lazy.grid.itemsIndexed
11 | import androidx.compose.foundation.shape.RoundedCornerShape
12 | import androidx.compose.material.*
13 | import androidx.compose.material.icons.Icons
14 | import androidx.compose.material.icons.filled.Check
15 | import androidx.compose.runtime.*
16 | import androidx.compose.ui.Alignment
17 | import androidx.compose.ui.Modifier
18 | import androidx.compose.ui.draw.clip
19 | import androidx.compose.ui.graphics.Color
20 | import androidx.compose.ui.platform.ClipboardManager
21 | import androidx.compose.ui.platform.LocalClipboardManager
22 | import androidx.compose.ui.platform.LocalContext
23 | import androidx.compose.ui.res.painterResource
24 | import androidx.compose.ui.text.AnnotatedString
25 | import androidx.compose.ui.text.font.FontWeight
26 | import androidx.compose.ui.text.style.TextAlign
27 | import androidx.compose.ui.unit.dp
28 | import androidx.compose.ui.unit.sp
29 | import com.smarttoolfactory.extendedcolors.ColorSwatch
30 | import com.smarttoolfactory.extendedcolors.parser.rememberColorParser
31 | import com.smarttoolfactory.extendedcolors.util.*
32 | import kotlinx.coroutines.Dispatchers
33 | import kotlinx.coroutines.flow.distinctUntilChanged
34 | import kotlinx.coroutines.flow.flowOn
35 | import kotlinx.coroutines.flow.mapLatest
36 |
37 |
38 | @Composable
39 | fun M3ColorPicker(onColorChange: (Color) -> Unit) {
40 |
41 |
42 | Column(
43 | modifier = Modifier
44 | .fillMaxSize()
45 | .background(Color.Black.copy(alpha = .8f)),
46 | horizontalAlignment = Alignment.CenterHorizontally
47 | ) {
48 |
49 | val colorNameParser = rememberColorParser()
50 |
51 | // Show primary or accent colors
52 | var primaryAccentSelection by remember {
53 | mutableStateOf(0)
54 | }
55 |
56 | // Index of selected list as main and index of color in that list
57 | val colorSelectionIndex =
58 | remember { ColorSelectionIndex(mainSelection = 0, subSelection = 0) }
59 |
60 | // This is the selected color swatch in top grid which is swatch/list of colors
61 | var colorSwatchIndex by remember { mutableStateOf(0) }
62 |
63 | val colorSwatch: LinkedHashMap CAM16 instances also have coordinates in the CAM16-UCS space, called J*, a*, b*, or jstar,
28 | * astar, bstar in code. CAM16-UCS is included in the CAM16 specification, and should be used when
29 | * measuring distances between colors.
30 | *
31 | * In traditional color spaces, a color can be identified solely by the observer's measurement of
32 | * the color. Color appearance models such as CAM16 also use information about the environment where
33 | * the color was observed, known as the viewing conditions.
34 | *
35 | * For example, white under the traditional assumption of a midday sun white point is accurately
36 | * measured as a slightly chromatic blue by CAM16. (roughly, hue 203, chroma 3, lightness 100)
37 | */
38 | public final class Cam16 {
39 | // Transforms XYZ color space coordinates to 'cone'/'RGB' responses in CAM16.
40 | static final double[][] XYZ_TO_CAM16RGB = {
41 | {0.401288, 0.650173, -0.051461},
42 | {-0.250268, 1.204414, 0.045854},
43 | {-0.002079, 0.048952, 0.953127}
44 | };
45 |
46 | // Transforms 'cone'/'RGB' responses in CAM16 to XYZ color space coordinates.
47 | static final double[][] CAM16RGB_TO_XYZ = {
48 | {1.8620678, -1.0112547, 0.14918678},
49 | {0.38752654, 0.62144744, -0.00897398},
50 | {-0.01584150, -0.03412294, 1.0499644}
51 | };
52 |
53 | // CAM16 color dimensions, see getters for documentation.
54 | private final double hue;
55 | private final double chroma;
56 | private final double j;
57 | private final double q;
58 | private final double m;
59 | private final double s;
60 |
61 | // Coordinates in UCS space. Used to determine color distance, like delta E equations in L*a*b*.
62 | private final double jstar;
63 | private final double astar;
64 | private final double bstar;
65 |
66 | /**
67 | * CAM16 instances also have coordinates in the CAM16-UCS space, called J*, a*, b*, or jstar,
68 | * astar, bstar in code. CAM16-UCS is included in the CAM16 specification, and is used to measure
69 | * distances between colors.
70 | */
71 | double distance(Cam16 other) {
72 | double dJ = getJstar() - other.getJstar();
73 | double dA = getAstar() - other.getAstar();
74 | double dB = getBstar() - other.getBstar();
75 | double dEPrime = Math.sqrt(dJ * dJ + dA * dA + dB * dB);
76 | double dE = 1.41 * Math.pow(dEPrime, 0.63);
77 | return dE;
78 | }
79 |
80 | /** Hue in CAM16 */
81 | public double getHue() {
82 | return hue;
83 | }
84 |
85 | /** Chroma in CAM16 */
86 | public double getChroma() {
87 | return chroma;
88 | }
89 |
90 | /** Lightness in CAM16 */
91 | public double getJ() {
92 | return j;
93 | }
94 |
95 | /**
96 | * Brightness in CAM16.
97 | *
98 | * Prefer lightness, brightness is an absolute quantity. For example, a sheet of white paper is
99 | * much brighter viewed in sunlight than in indoor light, but it is the lightest object under any
100 | * lighting.
101 | */
102 | public double getQ() {
103 | return q;
104 | }
105 |
106 | /**
107 | * Colorfulness in CAM16.
108 | *
109 | * Prefer chroma, colorfulness is an absolute quantity. For example, a yellow toy car is much
110 | * more colorful outside than inside, but it has the same chroma in both environments.
111 | */
112 | public double getM() {
113 | return m;
114 | }
115 |
116 | /**
117 | * Saturation in CAM16.
118 | *
119 | * Colorfulness in proportion to brightness. Prefer chroma, saturation measures colorfulness
120 | * relative to the color's own brightness, where chroma is colorfulness relative to white.
121 | */
122 | public double getS() {
123 | return s;
124 | }
125 |
126 | /** Lightness coordinate in CAM16-UCS */
127 | public double getJstar() {
128 | return jstar;
129 | }
130 |
131 | /** a* coordinate in CAM16-UCS */
132 | public double getAstar() {
133 | return astar;
134 | }
135 |
136 | /** b* coordinate in CAM16-UCS */
137 | public double getBstar() {
138 | return bstar;
139 | }
140 |
141 | /**
142 | * All of the CAM16 dimensions can be calculated from 3 of the dimensions, in the following
143 | * combinations: - {j or q} and {c, m, or s} and hue - jstar, astar, bstar Prefer using a static
144 | * method that constructs from 3 of those dimensions. This constructor is intended for those
145 | * methods to use to return all possible dimensions.
146 | *
147 | * @param hue for example, red, orange, yellow, green, etc.
148 | * @param chroma informally, colorfulness / color intensity. like saturation in HSL, except
149 | * perceptually accurate.
150 | * @param j lightness
151 | * @param q brightness; ratio of lightness to white point's lightness
152 | * @param m colorfulness
153 | * @param s saturation; ratio of chroma to white point's chroma
154 | * @param jstar CAM16-UCS J coordinate
155 | * @param astar CAM16-UCS a coordinate
156 | * @param bstar CAM16-UCS b coordinate
157 | */
158 | private Cam16(
159 | double hue,
160 | double chroma,
161 | double j,
162 | double q,
163 | double m,
164 | double s,
165 | double jstar,
166 | double astar,
167 | double bstar) {
168 | this.hue = hue;
169 | this.chroma = chroma;
170 | this.j = j;
171 | this.q = q;
172 | this.m = m;
173 | this.s = s;
174 | this.jstar = jstar;
175 | this.astar = astar;
176 | this.bstar = bstar;
177 | }
178 |
179 | /**
180 | * Create a CAM16 color from a color, assuming the color was viewed in default viewing conditions.
181 | *
182 | * @param argb ARGB representation of a color.
183 | */
184 | public static Cam16 fromInt(int argb) {
185 | return fromIntInViewingConditions(argb, ViewingConditions.DEFAULT);
186 | }
187 |
188 | /**
189 | * Create a CAM16 color from a color in defined viewing conditions.
190 | *
191 | * @param argb ARGB representation of a color.
192 | * @param viewingConditions Information about the environment where the color was observed.
193 | */
194 | // The RGB => XYZ conversion matrix elements are derived scientific constants. While the values
195 | // may differ at runtime due to floating point imprecision, keeping the values the same, and
196 | // accurate, across implementations takes precedence.
197 | @SuppressWarnings("FloatingPointLiteralPrecision")
198 | static Cam16 fromIntInViewingConditions(int argb, ViewingConditions viewingConditions) {
199 | // Transform ARGB int to XYZ
200 | int red = (argb & 0x00ff0000) >> 16;
201 | int green = (argb & 0x0000ff00) >> 8;
202 | int blue = (argb & 0x000000ff);
203 | double redL = ColorUtils.linearized(red);
204 | double greenL = ColorUtils.linearized(green);
205 | double blueL = ColorUtils.linearized(blue);
206 | double x = 0.41233895 * redL + 0.35762064 * greenL + 0.18051042 * blueL;
207 | double y = 0.2126 * redL + 0.7152 * greenL + 0.0722 * blueL;
208 | double z = 0.01932141 * redL + 0.11916382 * greenL + 0.95034478 * blueL;
209 |
210 | // Transform XYZ to 'cone'/'rgb' responses
211 | double[][] matrix = XYZ_TO_CAM16RGB;
212 | double rT = (x * matrix[0][0]) + (y * matrix[0][1]) + (z * matrix[0][2]);
213 | double gT = (x * matrix[1][0]) + (y * matrix[1][1]) + (z * matrix[1][2]);
214 | double bT = (x * matrix[2][0]) + (y * matrix[2][1]) + (z * matrix[2][2]);
215 |
216 | // Discount illuminant
217 | double rD = viewingConditions.getRgbD()[0] * rT;
218 | double gD = viewingConditions.getRgbD()[1] * gT;
219 | double bD = viewingConditions.getRgbD()[2] * bT;
220 |
221 | // Chromatic adaptation
222 | double rAF = Math.pow(viewingConditions.getFl() * Math.abs(rD) / 100.0, 0.42);
223 | double gAF = Math.pow(viewingConditions.getFl() * Math.abs(gD) / 100.0, 0.42);
224 | double bAF = Math.pow(viewingConditions.getFl() * Math.abs(bD) / 100.0, 0.42);
225 | double rA = Math.signum(rD) * 400.0 * rAF / (rAF + 27.13);
226 | double gA = Math.signum(gD) * 400.0 * gAF / (gAF + 27.13);
227 | double bA = Math.signum(bD) * 400.0 * bAF / (bAF + 27.13);
228 |
229 | // redness-greenness
230 | double a = (11.0 * rA + -12.0 * gA + bA) / 11.0;
231 | // yellowness-blueness
232 | double b = (rA + gA - 2.0 * bA) / 9.0;
233 |
234 | // auxiliary components
235 | double u = (20.0 * rA + 20.0 * gA + 21.0 * bA) / 20.0;
236 | double p2 = (40.0 * rA + 20.0 * gA + bA) / 20.0;
237 |
238 | // hue
239 | double atan2 = Math.atan2(b, a);
240 | double atanDegrees = Math.toDegrees(atan2);
241 | double hue =
242 | atanDegrees < 0
243 | ? atanDegrees + 360.0
244 | : atanDegrees >= 360 ? atanDegrees - 360.0 : atanDegrees;
245 | double hueRadians = Math.toRadians(hue);
246 |
247 | // achromatic response to color
248 | double ac = p2 * viewingConditions.getNbb();
249 |
250 | // CAM16 lightness and brightness
251 | double j =
252 | 100.0
253 | * Math.pow(
254 | ac / viewingConditions.getAw(),
255 | viewingConditions.getC() * viewingConditions.getZ());
256 | double q =
257 | 4.0
258 | / viewingConditions.getC()
259 | * Math.sqrt(j / 100.0)
260 | * (viewingConditions.getAw() + 4.0)
261 | * viewingConditions.getFlRoot();
262 |
263 | // CAM16 chroma, colorfulness, and saturation.
264 | double huePrime = (hue < 20.14) ? hue + 360 : hue;
265 | double eHue = 0.25 * (Math.cos(Math.toRadians(huePrime) + 2.0) + 3.8);
266 | double p1 = 50000.0 / 13.0 * eHue * viewingConditions.getNc() * viewingConditions.getNcb();
267 | double t = p1 * Math.hypot(a, b) / (u + 0.305);
268 | double alpha =
269 | Math.pow(1.64 - Math.pow(0.29, viewingConditions.getN()), 0.73) * Math.pow(t, 0.9);
270 | // CAM16 chroma, colorfulness, saturation
271 | double c = alpha * Math.sqrt(j / 100.0);
272 | double m = c * viewingConditions.getFlRoot();
273 | double s =
274 | 50.0 * Math.sqrt((alpha * viewingConditions.getC()) / (viewingConditions.getAw() + 4.0));
275 |
276 | // CAM16-UCS components
277 | double jstar = (1.0 + 100.0 * 0.007) * j / (1.0 + 0.007 * j);
278 | double mstar = 1.0 / 0.0228 * Math.log1p(0.0228 * m);
279 | double astar = mstar * Math.cos(hueRadians);
280 | double bstar = mstar * Math.sin(hueRadians);
281 |
282 | return new Cam16(hue, c, j, q, m, s, jstar, astar, bstar);
283 | }
284 |
285 | /**
286 | * @param j CAM16 lightness
287 | * @param c CAM16 chroma
288 | * @param h CAM16 hue
289 | */
290 | static Cam16 fromJch(double j, double c, double h) {
291 | return fromJchInViewingConditions(j, c, h, ViewingConditions.DEFAULT);
292 | }
293 |
294 | /**
295 | * @param j CAM16 lightness
296 | * @param c CAM16 chroma
297 | * @param h CAM16 hue
298 | * @param viewingConditions Information about the environment where the color was observed.
299 | */
300 | private static Cam16 fromJchInViewingConditions(
301 | double j, double c, double h, ViewingConditions viewingConditions) {
302 | double q =
303 | 4.0
304 | / viewingConditions.getC()
305 | * Math.sqrt(j / 100.0)
306 | * (viewingConditions.getAw() + 4.0)
307 | * viewingConditions.getFlRoot();
308 | double m = c * viewingConditions.getFlRoot();
309 | double alpha = c / Math.sqrt(j / 100.0);
310 | double s =
311 | 50.0 * Math.sqrt((alpha * viewingConditions.getC()) / (viewingConditions.getAw() + 4.0));
312 |
313 | double hueRadians = Math.toRadians(h);
314 | double jstar = (1.0 + 100.0 * 0.007) * j / (1.0 + 0.007 * j);
315 | double mstar = 1.0 / 0.0228 * Math.log1p(0.0228 * m);
316 | double astar = mstar * Math.cos(hueRadians);
317 | double bstar = mstar * Math.sin(hueRadians);
318 | return new Cam16(h, c, j, q, m, s, jstar, astar, bstar);
319 | }
320 |
321 | /**
322 | * Create a CAM16 color from CAM16-UCS coordinates.
323 | *
324 | * @param jstar CAM16-UCS lightness.
325 | * @param astar CAM16-UCS a dimension. Like a* in L*a*b*, it is a Cartesian coordinate on the Y
326 | * axis.
327 | * @param bstar CAM16-UCS b dimension. Like a* in L*a*b*, it is a Cartesian coordinate on the X
328 | * axis.
329 | */
330 | public static Cam16 fromUcs(double jstar, double astar, double bstar) {
331 |
332 | return fromUcsInViewingConditions(jstar, astar, bstar, ViewingConditions.DEFAULT);
333 | }
334 |
335 | /**
336 | * Create a CAM16 color from CAM16-UCS coordinates in defined viewing conditions.
337 | *
338 | * @param jstar CAM16-UCS lightness.
339 | * @param astar CAM16-UCS a dimension. Like a* in L*a*b*, it is a Cartesian coordinate on the Y
340 | * axis.
341 | * @param bstar CAM16-UCS b dimension. Like a* in L*a*b*, it is a Cartesian coordinate on the X
342 | * axis.
343 | * @param viewingConditions Information about the environment where the color was observed.
344 | */
345 | public static Cam16 fromUcsInViewingConditions(
346 | double jstar, double astar, double bstar, ViewingConditions viewingConditions) {
347 |
348 | double m = Math.hypot(astar, bstar);
349 | double m2 = Math.expm1(m * 0.0228) / 0.0228;
350 | double c = m2 / viewingConditions.getFlRoot();
351 | double h = Math.atan2(bstar, astar) * (180.0 / Math.PI);
352 | if (h < 0.0) {
353 | h += 360.0;
354 | }
355 | double j = jstar / (1. - (jstar - 100.) * 0.007);
356 | return fromJchInViewingConditions(j, c, h, viewingConditions);
357 | }
358 |
359 | /**
360 | * ARGB representation of the color. Assumes the color was viewed in default viewing conditions,
361 | * which are near-identical to the default viewing conditions for sRGB.
362 | */
363 | public int toInt() {
364 | return viewed(ViewingConditions.DEFAULT);
365 | }
366 |
367 | /**
368 | * ARGB representation of the color, in defined viewing conditions.
369 | *
370 | * @param viewingConditions Information about the environment where the color will be viewed.
371 | * @return ARGB representation of color
372 | */
373 | int viewed(ViewingConditions viewingConditions) {
374 | double alpha =
375 | (getChroma() == 0.0 || getJ() == 0.0) ? 0.0 : getChroma() / Math.sqrt(getJ() / 100.0);
376 |
377 | double t =
378 | Math.pow(
379 | alpha / Math.pow(1.64 - Math.pow(0.29, viewingConditions.getN()), 0.73), 1.0 / 0.9);
380 | double hRad = Math.toRadians(getHue());
381 |
382 | double eHue = 0.25 * (Math.cos(hRad + 2.0) + 3.8);
383 | double ac =
384 | viewingConditions.getAw()
385 | * Math.pow(getJ() / 100.0, 1.0 / viewingConditions.getC() / viewingConditions.getZ());
386 | double p1 = eHue * (50000.0 / 13.0) * viewingConditions.getNc() * viewingConditions.getNcb();
387 | double p2 = (ac / viewingConditions.getNbb());
388 |
389 | double hSin = Math.sin(hRad);
390 | double hCos = Math.cos(hRad);
391 |
392 | double gamma = 23.0 * (p2 + 0.305) * t / (23.0 * p1 + 11.0 * t * hCos + 108.0 * t * hSin);
393 | double a = gamma * hCos;
394 | double b = gamma * hSin;
395 | double rA = (460.0 * p2 + 451.0 * a + 288.0 * b) / 1403.0;
396 | double gA = (460.0 * p2 - 891.0 * a - 261.0 * b) / 1403.0;
397 | double bA = (460.0 * p2 - 220.0 * a - 6300.0 * b) / 1403.0;
398 |
399 | double rCBase = max(0, (27.13 * Math.abs(rA)) / (400.0 - Math.abs(rA)));
400 | double rC =
401 | Math.signum(rA) * (100.0 / viewingConditions.getFl()) * Math.pow(rCBase, 1.0 / 0.42);
402 | double gCBase = max(0, (27.13 * Math.abs(gA)) / (400.0 - Math.abs(gA)));
403 | double gC =
404 | Math.signum(gA) * (100.0 / viewingConditions.getFl()) * Math.pow(gCBase, 1.0 / 0.42);
405 | double bCBase = max(0, (27.13 * Math.abs(bA)) / (400.0 - Math.abs(bA)));
406 | double bC =
407 | Math.signum(bA) * (100.0 / viewingConditions.getFl()) * Math.pow(bCBase, 1.0 / 0.42);
408 | double rF = rC / viewingConditions.getRgbD()[0];
409 | double gF = gC / viewingConditions.getRgbD()[1];
410 | double bF = bC / viewingConditions.getRgbD()[2];
411 |
412 | double[][] matrix = CAM16RGB_TO_XYZ;
413 | double x = (rF * matrix[0][0]) + (gF * matrix[0][1]) + (bF * matrix[0][2]);
414 | double y = (rF * matrix[1][0]) + (gF * matrix[1][1]) + (bF * matrix[1][2]);
415 | double z = (rF * matrix[2][0]) + (gF * matrix[2][1]) + (bF * matrix[2][2]);
416 |
417 | return ColorUtils.argbFromXyz(x, y, z);
418 | }
419 | }
420 |
--------------------------------------------------------------------------------