Put a transparent NSWindow permanently on top of another NSWindow

情到浓时终转凉″ 提交于 2019-11-27 21:37:14
dzolanta

Child window is what you need.

Create NSWindow with NSBorderlessWindowMask and define it to be transparent using - setOpaque: and - setBackgroundColor: methods. Then add newly created window as a child of window containing an instance of NSWebView (using NSWindow's - addChildWindow:ordered: method). Moving parent window will automatically cause child window to move.

Update with working code:

CGRect wRect = self.window.frame;
NSView *contentView  =self.window.contentView;
CGRect cRect = contentView.frame;

CGRect rect = CGRectMake(wRect.origin.x, wRect.origin.y, cRect.size.width, cRect.size.height);
NSWindow *overlayWindow = [[NSWindow alloc]initWithContentRect:rect 
                                                     styleMask:NSBorderlessWindowMask 
                                                       backing:NSBackingStoreBuffered 
                                                         defer:NO];
overlayWindow.backgroundColor = [NSColor redColor];
[overlayWindow setOpaque:NO];
overlayWindow.alphaValue = 0.5f;

[self.window addChildWindow:overlayWindow ordered:NSWindowAbove];

Swift 3 version using window controller:

final class OverlayWindowController: NSWindowController {
  init(frame: NSRect) {
    let window = NSWindow(contentRect: frame, styleMask: .borderless, backing: .buffered, defer: false)
    super.init(window: window)

    window.contentViewController = MyViewController()
    window.backgroundColor = NSColor.clear
    window.isOpaque = false
  }

  @available(*, unavailable)
  required init?(coder: NSCoder) {
    fatalError("init(coder:) is unavailable")
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!