Created
July 18, 2016 10:40
-
-
Save kakajika/f1eb84b3ef4708e82abfc20f74a39a57 to your computer and use it in GitHub Desktop.
Utility class for HSL color in Android.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.graphics.Color; | |
import android.support.annotation.ColorInt; | |
import android.support.annotation.NonNull; | |
import android.support.annotation.Size; | |
public class ColorUtil { | |
public static @ColorInt int lighten(@ColorInt int color, float value) { | |
float[] hsl = colorToHSL(color); | |
hsl[2] += value / 100; | |
hsl[2] = Math.max(0f, Math.min(hsl[2], 1f)); | |
return HSLToColor(hsl); | |
} | |
public static @ColorInt int darken(@ColorInt int color, float value) { | |
float[] hsl = colorToHSL(color); | |
hsl[2] -= value / 100; | |
hsl[2] = Math.max(0f, Math.min(hsl[2], 1f)); | |
return HSLToColor(hsl); | |
} | |
public static @NonNull @Size(3) float[] colorToHSL(@ColorInt int color) { | |
return colorToHSL(color, new float[3]); | |
} | |
public static @NonNull @Size(3) float[] colorToHSL(@ColorInt int color, @NonNull @Size(3) float[] hsl) { | |
final float r = Color.red(color) / 255f; | |
final float g = Color.green(color) / 255f; | |
final float b = Color.blue(color) / 255f; | |
final float max = Math.max(r, Math.max(g, b)), min = Math.min(r, Math.min(g, b)); | |
hsl[2] = (max + min) / 2; | |
if (max == min) { | |
hsl[0] = hsl[1] = 0; | |
} else { | |
float d = max - min; | |
//noinspection Range | |
hsl[1] = (hsl[2] > 0.5f) ? d / (2 - max - min) : d / (max + min); | |
if (max == r) hsl[0] = (g - b) / d + (g < b ? 6 : 0); | |
else if (max == g) hsl[0] = (b - r) / d + 2; | |
else if (max == b) hsl[0] = (r - g) / d + 4; | |
hsl[0] /= 6; | |
} | |
return hsl; | |
} | |
public static @ColorInt int HSLToColor(@NonNull @Size(3) float[] hsl) { | |
float r, g, b; | |
final float h = hsl[0]; | |
final float s = hsl[1]; | |
final float l = hsl[2]; | |
if (s == 0) { | |
r = g = b = l; | |
} else { | |
float q = l < 0.5f ? l * (1 + s) : l + s - l * s; | |
float p = 2 * l - q; | |
r = hue2rgb(p, q, h + 1f/3); | |
g = hue2rgb(p, q, h); | |
b = hue2rgb(p, q, h - 1f/3); | |
} | |
return Color.rgb((int) (r*255), (int) (g*255), (int) (b*255)); | |
} | |
private static float hue2rgb(float p, float q, float t) { | |
if(t < 0) t += 1; | |
if(t > 1) t -= 1; | |
if(t < 1f/6) return p + (q - p) * 6 * t; | |
if(t < 1f/2) return q; | |
if(t < 2f/3) return p + (q - p) * (2f/3 - t) * 6; | |
return p; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment