DynamicGlucoseColor.swift 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import Foundation
  2. import SwiftUI
  3. // Helper function to decide how to pick the glucose color
  4. public func getDynamicGlucoseColor(
  5. glucoseValue: Decimal,
  6. highGlucoseColorValue: Decimal,
  7. lowGlucoseColorValue: Decimal,
  8. targetGlucose: Decimal,
  9. glucoseColorStyle: GlucoseColorStyle,
  10. offset: Decimal
  11. ) -> Color {
  12. // Convert Decimal to Int for high and low glucose values
  13. let lowGlucose = lowGlucoseColorValue - offset
  14. let highGlucose = highGlucoseColorValue + (offset * 1.75)
  15. let targetGlucose = targetGlucose
  16. // Only use calculateHueBasedGlucoseColor if the setting is enabled in preferences
  17. if GlucoseColorStyle == .dynamicColor {
  18. return calculateHueBasedGlucoseColor(
  19. glucoseValue: glucoseValue,
  20. highGlucose: highGlucose,
  21. lowGlucose: lowGlucose,
  22. targetGlucose: targetGlucose
  23. )
  24. }
  25. // Otheriwse, use static (orange = high, red = low, green = range)
  26. else {
  27. if glucoseValue > highGlucose {
  28. return Color.orange
  29. } else if glucoseValue < lowGlucose {
  30. return Color.red
  31. } else {
  32. return Color.green
  33. }
  34. }
  35. }
  36. // Dynamic color - Define the hue values for the key points
  37. // We'll shift color gradually one glucose point at a time
  38. // We'll shift through the rainbow colors of ROY-G-BIV from low to high
  39. // Start at red for lowGlucose, green for targetGlucose, and violet for highGlucose
  40. public func calculateHueBasedGlucoseColor(
  41. glucoseValue: Decimal,
  42. highGlucose: Decimal,
  43. lowGlucose: Decimal,
  44. targetGlucose: Decimal
  45. ) -> Color {
  46. let redHue: CGFloat = 0.0 / 360.0 // 0 degrees
  47. let greenHue: CGFloat = 120.0 / 360.0 // 120 degrees
  48. let purpleHue: CGFloat = 270.0 / 360.0 // 270 degrees
  49. // Calculate the hue based on the bgLevel
  50. var hue: CGFloat
  51. if glucoseValue <= lowGlucose {
  52. hue = redHue
  53. } else if glucoseValue >= highGlucose {
  54. hue = purpleHue
  55. } else if glucoseValue <= targetGlucose {
  56. // Interpolate between red and green
  57. let ratio = CGFloat(truncating: (glucoseValue - lowGlucose) / (targetGlucose - lowGlucose) as NSNumber)
  58. hue = redHue + ratio * (greenHue - redHue)
  59. } else {
  60. // Interpolate between green and purple
  61. let ratio = CGFloat(truncating: (glucoseValue - targetGlucose) / (highGlucose - targetGlucose) as NSNumber)
  62. hue = greenHue + ratio * (purpleHue - greenHue)
  63. }
  64. // Return the color with full saturation and brightness
  65. let color = Color(hue: hue, saturation: 0.6, brightness: 0.9)
  66. return color
  67. }