DynamicGlucoseColor.swift 2.4 KB

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