[wpilib] Add hex string constructor to Color and Color8Bit (#5063)

Co-authored-by: Tyler Veness <calcmogul@gmail.com>
This commit is contained in:
Sriman Achanta
2023-12-01 13:26:58 -05:00
committed by GitHub
parent 74b85b76a9
commit 7ed900ae3a
10 changed files with 401 additions and 5 deletions

View File

@@ -21,6 +21,13 @@ public class Color {
public final double blue;
private String m_name;
/** Constructs a default color (black). */
public Color() {
red = 0.0;
green = 0.0;
blue = 0.0;
}
/**
* Constructs a Color from doubles.
*
@@ -69,6 +76,22 @@ public class Color {
this.m_name = name;
}
/**
* Constructs a Color from a hex string.
*
* @param hexString a string of the format <code>#RRGGBB</code>
* @throws IllegalArgumentException if the hex string is invalid.
*/
public Color(String hexString) {
if (hexString.length() != 7 || !hexString.startsWith("#")) {
throw new IllegalArgumentException("Invalid hex string \"" + hexString + "\"");
}
this.red = Integer.valueOf(hexString.substring(1, 3), 16) / 255.0;
this.green = Integer.valueOf(hexString.substring(3, 5), 16) / 255.0;
this.blue = Integer.valueOf(hexString.substring(5, 7), 16) / 255.0;
}
/**
* Creates a Color from HSV values.
*

View File

@@ -14,6 +14,13 @@ public class Color8Bit {
public final int green;
public final int blue;
/** Constructs a default color (black). */
public Color8Bit() {
red = 0;
green = 0;
blue = 0;
}
/**
* Constructs a Color8Bit.
*
@@ -36,6 +43,22 @@ public class Color8Bit {
this((int) (color.red * 255), (int) (color.green * 255), (int) (color.blue * 255));
}
/**
* Constructs a Color8Bit from a hex string.
*
* @param hexString a string of the format <code>#RRGGBB</code>
* @throws IllegalArgumentException if the hex string is invalid.
*/
public Color8Bit(String hexString) {
if (hexString.length() != 7 || !hexString.startsWith("#")) {
throw new IllegalArgumentException("Invalid hex string \"" + hexString + "\"");
}
this.red = Integer.valueOf(hexString.substring(1, 3), 16);
this.green = Integer.valueOf(hexString.substring(3, 5), 16);
this.blue = Integer.valueOf(hexString.substring(5, 7), 16);
}
@Override
public boolean equals(Object other) {
if (this == other) {