parse static method

Color parse(
  1. String colorCode
)

Parses the color code as a Color literal and returns its value. Example, *

  • Color.parse("#ffe");
    
  • Color.parse("#73b5a9");
    
  • Color.parse("white");
    
  • Color.parse("rgba(100, 80, 100%, 0.5)");
    
  • Color.parse("hsl(100, 65%, 100%, 0.5)");
    
  • Notice: it recognized 17 standard colors:
  • aqua, black, blue, fuchsia, gray, grey, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow.

Implementation

static Color parse(String colorCode) {
  final len = (colorCode = colorCode.trim()).length;
  try {
    if (colorCode.codeUnitAt(0) == 35) { //#
      final step = len <= 4 ? 1: 2;
      List<int> rgb = [0, 0, 0];
      for (int i = 1, j = 0; i < len && j < 3; i += step, ++j) {
        rgb[j] = int.parse(colorCode.substring(i, i + step), radix: 16);
        if (step == 1)
          rgb[j] = (rgb[j] * 255) ~/ 15;
      }
      return Color(rgb[0], rgb[1], rgb[2]);
    } else {
      final k = colorCode.indexOf('(');
      if (k >= 0) {
        List<num> val = [0, 0, 0, 1];
        List<bool> hundredth = [false, false, false, false];

        int i = colorCode.indexOf(')', k + 1);
        final args = (i >= 0 ? colorCode.substring(k + 1, i): colorCode.substring(k + 1)).split(',');
        for (i = 0; i < 4 && i < args.length; ++i) {
          String arg = args[i].trim();
          hundredth[i] = arg.endsWith("%");
          if (hundredth[i])
            arg = arg.substring(0, arg.length - 1).trim();
          val[i] = arg.contains('.') ? double.parse(arg): int.parse(arg);
        }

        final type = colorCode.substring(0, k).trim().toLowerCase();
        switch (type) {
          case "rgb":
          case "rgba":
            if (hundredth[3])
              val[3] = val[3] / 100;
            for (int i = 0; i < 3; ++i)
              if (hundredth[i])
                val[i] = (255 * val[i]) ~/ 100;
            return Color(val[0], val[1], val[2], val[3]);

          case "hsl":
          case "hsla":
          case "hsv":
          case "hsva":
            if (hundredth[0])
              val[0] = (360 * val[0]) / 100;
            for (int i = 1; i < 4; ++i)
              if (hundredth[i])
                val[i] /= 100;
            return type.startsWith("hsl") ?
              HslColor(val[0], val[1], val[2], val[3]):
              HsvColor(val[0], val[1], val[2], val[3]);
        }
      } else {
        final color = _stdcolors[colorCode.toLowerCase()];
        if (color != null)
          return color;
      }
    }
  } catch (e) {
    throw FormatException(colorCode);
  }
  throw FormatException(colorCode);
}