Sunday, 27 April 2014

Libgdx - parse Color from String hex to 3x float -> new Color( float, float, float, float)

Here is short code. Very lazy but it works anyway. I ommited transparency.
This code converts String hext to three floats with alpha level 1

 public static Color parseColor(String hex) {  
      String s1 = hex.substring(0, 2);  
      int v1 = Integer.parseInt(s1, 16);  
      float f1 = (float) v1 / 255f;  
      String s2 = hex.substring(2, 4);  
      int v2 = Integer.parseInt(s2, 16);  
      float f2 = (float) v2 / 255f;  
      String s3 = hex.substring(4, 6);  
      int v3 = Integer.parseInt(s3, 16);  
      float f3 = (float) v3 / 255f;  
      return new Color(f1, f2, f3, 1);  
 }  

Example:

 interface Pallete {  
      public static Color blue = parseColor("33B5E5");  
      public static Color violet = parseColor("AA66CC");  
      public static Color green = parseColor("99CC00");  
      public static Color orange = parseColor("FFBB33");  
      public static Color red = parseColor("FF4444");  
      public static Color yellow = parseColor("FFDE00");  
      public static Color brown = parseColor("593E1A");  
      public static Color gray = parseColor("BDD8DA");  
      //  
      public static Color white = parseColor("FFFFFF");  
      public static Color black = parseColor("000000");  
 }