DynamicGlucoseColor.swift 2.5 KB

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