Skip to content

Commit 36ee93e

Browse files
hansonrhansonr
authored andcommitted
Adds getColorFromName using great canvas pixel trick
1 parent 86b9e85 commit 36ee93e

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

sources/net.sf.j2s.java.core/src/swingjs/JSUtil.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package swingjs;
22

3+
import java.awt.Color;
34
import java.awt.JSComponent;
45
import java.awt.Toolkit;
56
import java.io.BufferedInputStream;
@@ -628,5 +629,31 @@ public static boolean isOverridden(Object c, String name, Class<?> cl) {
628629
return cl == null || c != null && !isForClass(getJ2SAlias(c, name), cl);
629630
}
630631

632+
static Object ctxTemp;
633+
634+
/**
635+
* A great trick to get a Java Color from a name using JavaScript.
636+
* https://stackoverflow.com/questions/1573053/javascript-function-to-convert-color-names-to-hex-codes
637+
*
638+
* @param c
639+
* @return
640+
*/
641+
@SuppressWarnings({ "null" })
642+
public static Color getColorFromName(String c) {
643+
int[] rgb = null;
644+
/**
645+
* @j2sNative
646+
*
647+
* if (C$.ctxTemp == null) {
648+
* var d = document.createElement("canvas");
649+
* d.height = d.width = 1;
650+
* C$.ctxTemp = d.getContext("2d");
651+
* }
652+
* C$.ctxTemp.fillStyle = c;
653+
* C$.ctxTemp.fillRect(0, 0, 1, 1);
654+
* rgb = C$.ctxTemp.getImageData(0, 0, 1, 1).data;
655+
*/
656+
return new Color(rgb[0], rgb[1], rgb[2]);
657+
}
631658
}
632659

0 commit comments

Comments
 (0)