简体   繁体   English

在另一个NSView(特别是WebView)上绘制透明的覆盖层

[英]Draw a transparent overlay over another NSView, specifically, a WebView

I need to draw a transparent overlay over another NSView, specifically, a WebView. 我需要在另一个NSView(特别是WebView)上绘制透明的覆盖层。 The goal is to display some notification text with a semi-transparent background. 目的是显示一些具有半透明背景的通知文本。 For my first experiment I created an Overlay view that just displays a green square: 在我的第一个实验中,我创建了一个仅显示绿色正方形的“覆盖”视图:

class Overlay: NSView {
    override func drawRect(dirtyRect: NSRect) {
        NSColor.greenColor().setFill()
        NSBezierPath(rect: CGRect(x: 10, y: 10, width: 1000, height: 1000)).fill()
    }
}

and then, in my code, I instantiate them and add them like this: 然后,在我的代码中,实例化它们并像这样添加它们:

webView = WebView(frame: bounds)
overlay = Overlay(frame: bounds)

addSubview(webView)
addSubview(overlay)

To my surprise, that only works with some pages. 令我惊讶的是,这仅适用于某些页面。 For example, if you go to https://twitter.com/screensavrninja , it grayes out the whole page and shows you a sign out pop-in. 例如,如果您访问https://twitter.com/screensavrninja ,它将使整个页面显示为灰色,并向您显示退出弹出窗口。 Both the graying out and the pop-in happen on top of the green square. 变灰和弹出都在绿色方块的顶部。

Why is that happening? 为什么会这样呢? What's the appropriate way to have an overlay and have it remain on top? 有什么合适的方法可以使覆盖物保持在顶部?

In AppKit, the order of subviews does not necessarily determine the order that they will be drawn in. 在AppKit中,子视图的顺序不一定确定绘制它们的顺序。

For performance reasons, Cocoa does not enforce clipping among sibling views or guarantee correct invalidation and drawing behavior when sibling views overlap. 出于性能方面的考虑,当同级视图重叠时,Cocoa不会在同级视图之间强制剪切或保证正确的无效和绘制行为。 If you want a view to be drawn in front of another view, you should make the front view a subview (or descendant) of the rear view. 如果要在另一个视图前面绘制一个视图,则应将前视图作为后视图的子视图(或后代)。

Reference 参考

However, if you make the view layer-backed, they respect the ordering . 但是,如果您使视图成为分层支持,则它们会遵循顺序 So you could try enabling that. 因此,您可以尝试启用它。

Otherwise, you could use a child window to show the overlay. 否则,您可以使用子窗口显示叠加层。 This has the advantage of being able to extend beyond the bounds of the parent, and is fairly common in Cocoa. 这具有能够扩展到父代范围之外的优点,并且在可可中相当普遍。 See the documentation for NSWindow . 请参阅NSWindow文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM