How to reproduce this Xcode blue drag line

前端 未结 3 1797
轻奢々
轻奢々 2020-12-13 22:54

I\'d like to reproduce the Xcode blue drag line in my app.

Do you know a way to code this ?

I know how to draw a line using Core Graphics ... But th

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 23:24

    Using a transparent NSWindow :

    var window: NSWindow!
    
    func createLinePath(from: NSPoint, to: NSPoint) -> CGPath {
        let path = CGMutablePath()
    
        path.move(to: from)
        path.addLine(to: to)
    
        return path
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        //Transparent window
        window = NSWindow()
        window.styleMask = .borderless
        window.backgroundColor = .clear
        window.isOpaque = false
        window.hasShadow = false
    
        //Line
        let line = CAShapeLayer()
    
        line.path = createLinePath(from: NSPoint(x: 0, y: 0), to: NSPoint(x: 100, y: 100))
        line.lineWidth = 10.0
        line.strokeColor = NSColor.blue.cgColor
    
        //Update
        NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved]) {
            let newPos = NSEvent.mouseLocation()
    
            line.path = self.createLinePath(from: NSPoint(x: 0, y: 0), to: newPos)
    
            return $0
        }
    
        window.contentView!.layer = line
        window.contentView!.wantsLayer = true
    
        window.setFrame(NSScreen.main()!.frame, display: true)
    
        window.makeKeyAndOrderFront(nil)
    }
    

提交回复
热议问题