DynamicGlucoseColor.swift 2.4 KB

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