Search code examples
macosswiftuigdi

How to draw a line in the Desktop Context or Device Context in SwiftUI on macOS


I am a newbie in SwiftUI and macOS. The title say is all, I gonna draw a line in the macOS desktop. It means I draw 1 line on the top layer of the desktop and I can interact with the desktop as usual. I have finished the same with GetWindowDC in winApi and GDI in C++.

The GetWindowDC function retrieves the device context (DC) for the entire window, including title bar, menus, and scroll bars.

How can I found the way to do it instead..

I have found

NSGraphicsContext.current!.cgContext

as the quite similar with WinApi but it still not worked for macOS


Solution

  • Update: I have found a workaround solution:

    1. I create a Floating Panel with the transparent backgrounds which is the inherited from NSPanel class.
    2. Then I add the setting:
    
          // Allow the pannel to be on top of almost all other windows
          self.isFloatingPanel = true
          self.level = .floating
        
          // Allow the pannel to appear in a fullscreen space
          self.collectionBehavior.insert(.fullScreenAuxiliary)
        
          // While we may set a title for the window, don't show it
          self.titleVisibility = .hidden
          self.titlebarAppearsTransparent = true
        
          // Since there is no titlebar make the window moveable by click-dragging on the background
          self.isMovableByWindowBackground = false
          // Allow user can interact with the desktop components under your panel.
          self.ignoresMouseEvents = true
    
    
    1. Draw something in this floating panel.

    Hope this information is useful.