color_helpers.dart 1.7 KB

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