from static method

PColor? from(
  1. Object? o
)

Implementation

static PColor? from(Object? o) {
  if (o == null) return null;

  if (o is PColor) return o;

  var s = o.toString().trim();

  if (s.startsWith('#')) {
    var hex = s.substring(1);

    var hexLng = hex.length;
    if (hexLng >= 6) {
      var r = int.tryParse(hex.substring(0, 2), radix: 16);
      var g = int.tryParse(hex.substring(2, 4), radix: 16);
      var b = int.tryParse(hex.substring(4, 6), radix: 16);

      if (r != null && g != null && b != null) {
        if (hexLng == 9) {
          var a = int.tryParse(hex.substring(6, 9), radix: 16);

          if (a != null) {
            return PColorRGBA(r, g, b, a / 255);
          }
        }

        return PColorRGB(r, g, b);
      }
    } else if (hexLng == 3) {
      var r =
          int.tryParse(hex.substring(0, 1) + hex.substring(0, 1), radix: 16);
      var g =
          int.tryParse(hex.substring(1, 2) + hex.substring(1, 2), radix: 16);
      var b =
          int.tryParse(hex.substring(2, 3) + hex.substring(2, 3), radix: 16);

      if (r != null && g != null && b != null) {
        return PColorRGB(r, g, b);
      }
    }
  }

  var m = RegExp(
          r'^(?:rgba?\(|\(?)?\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)?$')
      .firstMatch(s);

  if (m != null) {
    var r = int.tryParse(m.group(1) ?? '');
    var g = int.tryParse(m.group(2) ?? '');
    var b = int.tryParse(m.group(3) ?? '');

    var aStr = m.group(4) ?? '';

    double? a;
    if (aStr.contains('.')) {
      a = double.tryParse(aStr);
    } else {
      var aN = int.tryParse(aStr);
      a = aN != null ? aN / 255 : null;
    }

    if (r != null && g != null && b != null) {
      if (a != null) {
        return PColorRGBA(r, g, b, a);
      }
      return PColorRGB(r, g, b);
    }
  }

  return null;
}