MarkerView.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //
  2. // ChartMarkerView.swift
  3. // Charts
  4. //
  5. // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
  6. // A port of MPAndroidChart for iOS
  7. // Licensed under Apache License 2.0
  8. //
  9. // https://github.com/danielgindi/Charts
  10. //
  11. import Foundation
  12. import CoreGraphics
  13. #if canImport(AppKit)
  14. import AppKit
  15. #endif
  16. @objc(ChartMarkerView)
  17. open class MarkerView: NSUIView, Marker
  18. {
  19. open var offset: CGPoint = CGPoint()
  20. @objc open weak var chartView: ChartViewBase?
  21. open func offsetForDrawing(atPoint point: CGPoint) -> CGPoint
  22. {
  23. guard let chart = chartView else { return self.offset }
  24. var offset = self.offset
  25. let width = self.bounds.size.width
  26. let height = self.bounds.size.height
  27. if point.x + offset.x < 0.0
  28. {
  29. offset.x = -point.x
  30. }
  31. else if point.x + width + offset.x > chart.bounds.size.width
  32. {
  33. offset.x = chart.bounds.size.width - point.x - width
  34. }
  35. if point.y + offset.y < 0
  36. {
  37. offset.y = -point.y
  38. }
  39. else if point.y + height + offset.y > chart.bounds.size.height
  40. {
  41. offset.y = chart.bounds.size.height - point.y - height
  42. }
  43. return offset
  44. }
  45. open func refreshContent(entry: ChartDataEntry, highlight: Highlight)
  46. {
  47. // Do nothing here...
  48. }
  49. open func draw(context: CGContext, point: CGPoint)
  50. {
  51. let offset = self.offsetForDrawing(atPoint: point)
  52. context.saveGState()
  53. context.translateBy(x: point.x + offset.x,
  54. y: point.y + offset.y)
  55. NSUIGraphicsPushContext(context)
  56. self.nsuiLayer?.render(in: context)
  57. NSUIGraphicsPopContext()
  58. context.restoreGState()
  59. }
  60. @objc
  61. open class func viewFromXib(in bundle: Bundle = .main) -> MarkerView?
  62. {
  63. #if !os(OSX)
  64. return bundle.loadNibNamed(
  65. String(describing: self),
  66. owner: nil,
  67. options: nil)?[0] as? MarkerView
  68. #else
  69. var loadedObjects = NSArray()
  70. let loadedObjectsPointer = AutoreleasingUnsafeMutablePointer<NSArray?>(&loadedObjects)
  71. if bundle.loadNibNamed(
  72. NSNib.Name(String(describing: self)),
  73. owner: nil,
  74. topLevelObjects: loadedObjectsPointer)
  75. {
  76. return loadedObjects[0] as? MarkerView
  77. }
  78. return nil
  79. #endif
  80. }
  81. }