KMPostionIndicateView.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //
  2. // KMPostionIndicateView.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lizhe on 2023/11/22.
  6. //
  7. import Cocoa
  8. enum KMPositionIndicateViewStyle: Int {
  9. case topLeft = 0
  10. case topCenter = 1
  11. case topRight = 2
  12. case middleLeft = 3
  13. case middleCenter = 4
  14. case middleRight = 5
  15. case bottomLeft = 6
  16. case bottomCenter = 7
  17. case bottomRight = 8
  18. }
  19. class KMPostionIndicateView: NSView {
  20. var styleChangedCallBack: (() -> Void)?
  21. var isTile: Bool = false
  22. var style: KMPositionIndicateViewStyle = .middleCenter
  23. override func draw(_ dirtyRect: NSRect) {
  24. super.draw(dirtyRect)
  25. guard let context = NSGraphicsContext.current?.cgContext else { return }
  26. for i in 0..<3 {
  27. for j in 0..<3 {
  28. context.saveGState()
  29. context.translateBy(x: CGFloat(28 * j), y: CGFloat(Int(bounds.height) - 28 * i - 24))
  30. context.addRect(CGRect(x: 0, y: 0, width: 24, height: 24))
  31. if style == KMPositionIndicateViewStyle(rawValue: j + 3 * i) {
  32. context.setFillColor(KMAppearance.Interactive.a0Color().cgColor)
  33. } else {
  34. context.setFillColor(KMAppearance.KM_DBDBDB_Color().cgColor)
  35. }
  36. context.fillPath()
  37. context.restoreGState()
  38. }
  39. }
  40. }
  41. override func mouseDown(with event: NSEvent) {
  42. let eventLocation = event.locationInWindow
  43. let localPoint = convert(eventLocation, from: nil)
  44. if isTile {
  45. return
  46. }
  47. let newStyle = styleForPoint(localPoint)
  48. if style != newStyle, let styleChangedCallBack = styleChangedCallBack {
  49. style = newStyle
  50. styleChangedCallBack()
  51. setNeedsDisplay(bounds)
  52. }
  53. }
  54. func styleForPoint(_ point: NSPoint) -> KMPositionIndicateViewStyle {
  55. for i in 0..<3 {
  56. for j in 0..<3 {
  57. let rect = NSRect(x: CGFloat(28 * j), y: CGFloat(Int(bounds.height) - 28 * i - 24), width: 24, height: 24)
  58. if rect.contains(point) {
  59. return KMPositionIndicateViewStyle(rawValue: j + 3 * i) ?? .middleCenter
  60. }
  61. }
  62. }
  63. return .middleCenter
  64. }
  65. }