如何从JavaFX ColorPicker颜色获取hex web String?

Zon*_*Zon 11 rgb hex javafx colors

我在JavaFX ColorPicker中选择了Color.现在我需要将其保存为十六进制字符串.我发现了这种方法,但对于JavaFX,它不适用.JavaFX有自己的Color类,没有getRGB()方法,可以用作mediatory转换.

小智 35

将颜色转换为Web颜色代码:

public class FxUtils
{
    public static String toRGBCode( Color color )
    {
        return String.format( "#%02X%02X%02X",
            (int)( color.getRed() * 255 ),
            (int)( color.getGreen() * 255 ),
            (int)( color.getBlue() * 255 ) );
    }
}
Run Code Online (Sandbox Code Playgroud)


Krö*_*röw 9

浮点安全方法:

// Helper method
private String format(double val) {
    String in = Integer.toHexString((int) Math.round(val * 255));
    return in.length() == 1 ? "0" + in : in;
}

public String toHexString(Color value) {
    return "#" + (format(value.getRed()) + format(value.getGreen()) + format(value.getBlue()) + format(value.getOpacity()))
            .toUpperCase();
}
Run Code Online (Sandbox Code Playgroud)

由于浮点表示和转换,目前投票最高的答案对于许多可能的Color对象实际上并不安全。使用可以Math.round(...)解决这个问题。

我正在Color使用Math.random()Color.hsb(...)方法使用随机双打(来自)生成对象。不使用Math.round(),转换后的十六进制代码是关闭的。如果您采用类似的方法来生成颜色,建议使用此方法,因为它更安全。


Zon*_*Zon 2

这个脆弱的解决方案完美地解决了这个问题:

// 8 symbols.
String hex1 = Integer.toHexString(myColorPicker.getValue().hashCode()); 

// With # prefix.
String hex2 = "#" + Integer.toHexString(myColorPicker.getValue().hashCode()); 

// 6 symbols in capital letters.
String hex3 = Integer.toHexString(myColorPicker.getValue().hashCode()).substring(0, 6).toUpperCase();
Run Code Online (Sandbox Code Playgroud)

  • 这是一个脆弱的解决方案。哈希码的生成取决于实现,因此不能确保在以后的版本中它可以工作。(例如,如果散列码中包含另一个字段,例如 opacy。) (7认同)