I want to use a custom hex color for google maps markers, but I saw you can only use hue colors from 0-360 and the 10 predefined ones. Is there any way you can change the marker color to be a hex one, or at least convert the hex value to hue so I can use that instead? I already know how to set a hue color to the marker, but not a hex one.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
The following code shows an example. It's based on this great answer that uses JavaScript: https://stackoverflow.com/a/3732187/1207156
public class Convert {
public static class Hsl {
public double h, s, l;
public Hsl(double h, double s, double l) {
this.h = h;
this.s = s;
this.l = l;
}
}
public static void main(String[] args) {
String color = "#c7d92c"; // A nice shade of green.
int r = Integer.parseInt(color.substring(1, 3), 16); // Grab the hex representation of red (chars 1-2) and convert to decimal (base 10).
int g = Integer.parseInt(color.substring(3, 5), 16);
int b = Integer.parseInt(color.substring(5, 7), 16);
double hue = rgbToHsl(r, g, b).h * 360;
System.out.println("The hue value is " + hue);
}
private static Hsl rgbToHsl(double r, double g, double b) {
r /= 255d; g /= 255d; b /= 255d;
double max = Math.max(Math.max(r, g), b), min = Math.min(Math.min(r, g), b);
double h, s, l = (max + min) / 2;
if (max == min) {
h = s = 0; // achromatic
} else {
double d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
if (max == r) h = (g - b) / d + (g < b ? 6 : 0);
else if (max == g) h = (b - r) / d + 2;
else h = (r - g) / d + 4; // if (max == b)
h /= 6;
}
return new Hsl(h, s, l);
}
}