color_helpers.dart 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * fluro
  3. * A Posse Production
  4. * http://goposse.com
  5. * Copyright (c) 2018 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,
  35. {ContrastPreference prefer = ContrastPreference.none}) {
  36. // Will return a value between 0.0 (black) and 1.0 (white)
  37. double value = (((sourceColor.red * 299.0) +
  38. (sourceColor.green * 587.0) +
  39. (sourceColor.blue * 114.0)) /
  40. 1000.0) /
  41. 255.0;
  42. if (prefer != ContrastPreference.none) {
  43. if (value >= _kMinContrastModifierRange &&
  44. value <= _kMaxContrastModifierRange) {
  45. return prefer == ContrastPreference.light
  46. ? new Color(0xFFFFFFFF)
  47. : new Color(0xFF000000);
  48. }
  49. }
  50. return value > 0.6 ? new Color(0xFF000000) : new Color(0xFFFFFFFF);
  51. }
  52. }