小智 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)
浮点安全方法:
// 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(),转换后的十六进制代码是关闭的。如果您采用类似的方法来生成颜色,建议使用此方法,因为它更安全。
这个脆弱的解决方案完美地解决了这个问题:
// 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)
| 归档时间: |
|
| 查看次数: |
15923 次 |
| 最近记录: |