How can I use NSVisualEffectView to blend window with background

时间秒杀一切 提交于 2020-01-02 08:02:25

问题


There seem to be a bunch of questions on this for old versions of Swift/Xcode, but for some reason it hasn't been working with the latest update. I created a NSVisualEffectView, blurryView, and added the subview to my main view:

class ViewController: NSViewController {
    @IBOutlet weak var blurryView: NSVisualEffectView! 
    override func viewDidLoad() {
        super.viewDidLoad()

        //background styling
        blurryView.wantsLayer = true
        blurryView.blendingMode = NSVisualEffectBlendingMode.behindWindow
        blurryView.material = NSVisualEffectMaterial.dark
        blurryView.state = NSVisualEffectState.active

        self.view.addSubview(blurryView, positioned: NSWindowOrderingMode.above, relativeTo: nil)

        // Do any additional setup after loading the view.
    }
...
}

But when I run it, there is no effect on the window. (when I set it to within window, and layer it on top of my other view, the blur works correctly, but I only want the window to blur.) I also tried doing the same thing in my App Delegate class, but I can't connect my window as an outlet, and therefore can't add the blurry view to the window. Here's what the code would look like:

class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application

        blurryView.wantsLayer = true
        blurryView.blendingMode = NSVisualEffectBlendingMode.withinWindow
        blurryView.material = NSVisualEffectMaterial.dark
        blurryView.state = NSVisualEffectState.active

        self.window.contentView?.addSubview(blurryView)

    }
...
}

To get an idea if what I'm looking for: NSVisualEffectView Vibrancy


回答1:


It works quite easy:

  1. In Interface Builder drag a NSVisualEffectView directly as a subview of the main view of your scene.
  2. In the Properties Inspector set Blending Mode to Behind Window
  3. Add the rest of the views you need as subviews of the NSVisualEffectView
  4. That's it, you're done

Here's an example:

Panel 1 View Controller is my blurred view, Background View is the first (non-blurred) view in my "real"view hierarchy.



来源:https://stackoverflow.com/questions/41475551/how-can-i-use-nsvisualeffectview-to-blend-window-with-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!