Skip to content

Commit 31bad79

Browse files
authored
Merge pull request #2613 from InkUisitor/feature/fix_color_isdark
fix(isdark): control both rgba and hexadecimal values
2 parents d1f37c7 + 07b3461 commit 31bad79

File tree

1 file changed

+36
-13
lines changed
  • source/src/main/java/org/cerberus/core/crud/entity

1 file changed

+36
-13
lines changed

source/src/main/java/org/cerberus/core/crud/entity/Label.java

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -144,25 +144,48 @@ public String guessFontColor() {
144144
return (this.isColorDark(this.getColor()) ? "white" : "black");
145145
}
146146

147-
public boolean isColorDark(String hexaCodeColor) {
147+
public boolean isColorDark(String colorCode) {
148148

149149
try {
150-
// remove hash character from string
151-
String rawFontColor = hexaCodeColor.substring(1, hexaCodeColor.length());
152-
153-
// convert hex string to int
154-
int rgb = Integer.parseInt(rawFontColor, 16);
155-
156-
Color c = new Color(rgb);
157-
158-
float[] hsb = Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(), null);
159-
150+
int red = 0;
151+
int green = 0;
152+
int blue = 0;
153+
154+
// Check if color is in RGBA format: rgba(r,g,b,a)
155+
if (colorCode != null && colorCode.toLowerCase().startsWith("rgba")) {
156+
// Extract RGBA values using regex
157+
String rgbaValues = colorCode.substring(colorCode.indexOf('(') + 1, colorCode.indexOf(')'));
158+
String[] values = rgbaValues.split(",");
159+
if (values.length >= 3) {
160+
red = Integer.parseInt(values[0].trim());
161+
green = Integer.parseInt(values[1].trim());
162+
blue = Integer.parseInt(values[2].trim());
163+
// values[3] is the alpha channel, which we don't need for brightness calculation
164+
}
165+
} else {
166+
// Handle hexadecimal color format: #RRGGBB or RRGGBB
167+
String rawFontColor = colorCode;
168+
if (rawFontColor.startsWith("#")) {
169+
rawFontColor = rawFontColor.substring(1);
170+
}
171+
172+
// convert hex string to int
173+
int rgb = Integer.parseInt(rawFontColor, 16);
174+
175+
Color c = new Color(rgb);
176+
red = c.getRed();
177+
green = c.getGreen();
178+
blue = c.getBlue();
179+
}
180+
181+
// Calculate brightness using RGB values
182+
float[] hsb = Color.RGBtoHSB(red, green, blue, null);
160183
float brightness = hsb[2];
161184

162-
LOG.debug("is the Color Dark ? " + hexaCodeColor + " : " + (brightness < 0.5));
185+
LOG.debug("is the Color Dark ? " + colorCode + " : " + (brightness < 0.5));
163186
return (brightness < 0.5);
164187
} catch (Exception e) {
165-
LOG.warn("Could not guess is color " + hexaCodeColor + "is Dark.", e);
188+
LOG.warn("Could not guess if color " + colorCode + " is Dark.", e);
166189
}
167190
return true;
168191
}

0 commit comments

Comments
 (0)