color_helpers.dart 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * router
  3. * A Posse Production
  4. * http://goposse.com
  5. * Copyright (c) 2017 Posse Productions LLC. All rights reserved.
  6. * See LICENSE for distribution and usage details.
  7. */
  8. import 'package:flutter/material.dart';
  9. enum ContrastPreference {
  10. none,
  11. light,
  12. dark,
  13. }
  14. class ColorHelpers {
  15. static int fromHexString(String argbHexString) {
  16. String useString = argbHexString;
  17. if (useString.startsWith("#")) {
  18. useString = useString.substring(1); // trim the starting '#'
  19. }
  20. if (useString.length < 8) {
  21. useString = "FF" + useString;
  22. }
  23. if (!useString.startsWith("0x")) {
  24. useString = "0x" + useString;
  25. }
  26. return int.parse(useString);
  27. }
  28. static final double _kMinContrastModifierRange = 0.35;
  29. static final double _kMaxContrastModifierRange = 0.65;
  30. /// Returns black or white depending on whether the source color is darker
  31. /// or lighter. If darker, will return white. If lighter, will return
  32. /// black. If the color is within 35-65% of the spectrum and a prefer
  33. /// value is specified, then white or black will be preferred.
  34. static Color blackOrWhiteContrastColor(Color sourceColor, {ContrastPreference prefer = ContrastPreference.none}) {
  35. // Will return a value between 0.0 (black) and 1.0 (white)
  36. double value = (((sourceColor.red * 299.0) + (sourceColor.green * 587.0) +
  37. (sourceColor.blue * 114.0)) / 1000.0) / 255.0;
  38. if (prefer != ContrastPreference.none) {
  39. if (value >= _kMinContrastModifierRange && value <= _kMaxContrastModifierRange) {
  40. return prefer == ContrastPreference.light ? new Color(0xFFFFFFFF) : new Color(0xFF000000);
  41. }
  42. }
  43. return value > 0.6 ? new Color(0xFF000000) : new Color(0xFFFFFFFF);
  44. }
  45. }