Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1.  
  2. import Cocoa
  3.  
  4. class JuxtaposeSlider: NSView {
  5.  
  6. // The slider's position is determined by a value between 0 and 1
  7. var value: CGFloat = 0.5
  8.  
  9. var rightImage = NSImage(named: "rightImage")
  10. var leftImage = NSImage(named: "leftImage")
  11.  
  12. @IBInspectable var handleColor: NSColor = .white
  13.  
  14. var mouseLocation: CGPoint? {
  15. didSet {
  16. if let location = self.mouseLocation {
  17. let local = self.convert(location, from: nil)
  18. self.value = min(1, max(0, local.x / self.bounds.width))
  19. }
  20. self.needsDisplay = true
  21. }
  22. }
  23.  
  24.  
  25.  
  26. // MARK: - Drawing
  27.  
  28. override func draw(_ dirtyRect: NSRect) {
  29. super.draw(dirtyRect)
  30.  
  31. // Draw the right image completely, as it is usually displayed somehow
  32. self.rightImage?.draw(at: .zero, from: self.bounds, operation: .copy, fraction: 1)
  33.  
  34. // Then draw the left image on top (partially)
  35. if self.value > 0 {
  36. let leftRect = NSRect(x: 0,
  37. y: 0,
  38. width: self.bounds.width * self.value,
  39. height: self.bounds.height)
  40. self.leftImage?.draw(at: .zero, from: leftRect, operation: .copy, fraction: 1)
  41. }
  42.  
  43.  
  44. // Draw a handle while dragging
  45. if self.mouseLocation == nil {return}
  46.  
  47. // You could also use an NSBezierPath for a more high-level API of drawing lines
  48. guard let context = NSGraphicsContext.current?.cgContext else {return}
  49.  
  50. self.handleColor.set()
  51.  
  52.  
  53. context.beginPath()
  54.  
  55. context.move(to: NSPoint(x: self.value * self.bounds.width,
  56. y: 0))
  57. context.addLine(to: NSPoint(x: self.value * self.bounds.width,
  58. y: self.bounds.size.height))
  59.  
  60. context.setLineWidth(4)
  61. context.strokePath()
  62.  
  63. }
  64.  
  65.  
  66. // MARK: - Event Handling
  67. override func mouseDown(with event: NSEvent) {
  68. self.mouseLocation = event.locationInWindow
  69. }
  70.  
  71. override func mouseDragged(with event: NSEvent) {
  72. self.mouseLocation = event.locationInWindow
  73. }
  74.  
  75. override func mouseUp(with event: NSEvent) {
  76. self.mouseLocation = nil
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement