Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Cocoa
- class JuxtaposeSlider: NSView {
- // The slider's position is determined by a value between 0 and 1
- var value: CGFloat = 0.5
- var rightImage = NSImage(named: "rightImage")
- var leftImage = NSImage(named: "leftImage")
- @IBInspectable var handleColor: NSColor = .white
- var mouseLocation: CGPoint? {
- didSet {
- if let location = self.mouseLocation {
- let local = self.convert(location, from: nil)
- self.value = min(1, max(0, local.x / self.bounds.width))
- }
- self.needsDisplay = true
- }
- }
- // MARK: - Drawing
- override func draw(_ dirtyRect: NSRect) {
- super.draw(dirtyRect)
- // Draw the right image completely, as it is usually displayed somehow
- self.rightImage?.draw(at: .zero, from: self.bounds, operation: .copy, fraction: 1)
- // Then draw the left image on top (partially)
- if self.value > 0 {
- let leftRect = NSRect(x: 0,
- y: 0,
- width: self.bounds.width * self.value,
- height: self.bounds.height)
- self.leftImage?.draw(at: .zero, from: leftRect, operation: .copy, fraction: 1)
- }
- // Draw a handle while dragging
- if self.mouseLocation == nil {return}
- // You could also use an NSBezierPath for a more high-level API of drawing lines
- guard let context = NSGraphicsContext.current?.cgContext else {return}
- self.handleColor.set()
- context.beginPath()
- context.move(to: NSPoint(x: self.value * self.bounds.width,
- y: 0))
- context.addLine(to: NSPoint(x: self.value * self.bounds.width,
- y: self.bounds.size.height))
- context.setLineWidth(4)
- context.strokePath()
- }
- // MARK: - Event Handling
- override func mouseDown(with event: NSEvent) {
- self.mouseLocation = event.locationInWindow
- }
- override func mouseDragged(with event: NSEvent) {
- self.mouseLocation = event.locationInWindow
- }
- override func mouseUp(with event: NSEvent) {
- self.mouseLocation = nil
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement