Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a window with transparent background with swift on osx?

Tags:

macos

swift

cocoa

I want to create an osx/cocoa application on my mac, which does something very simple: Display a text string on my mac, with no background. Ultimately this will be a timer which displays as an overlay on top of other windows, without being too intrusive.

I tried setting window.backgroundColor = NSColor(red: 1.0, green:0.5, blue:0.5, alpha: 0.5) (see the alpha is 0.5), in applicationDidFinishLaunching but this doesn't turn it into something remotely transparent.

Any good soul wants to suggest a way to do this?

like image 619
sagism Avatar asked Dec 30 '15 14:12

sagism


People also ask

How do you make a window transparent on a Mac?

Make the desktop less transparent: Choose Apple menu > System Preferences, click Accessibility , click Display, click Display, then select “Reduce transparency.” The transparent areas of the desktop and app windows become gray.

How do I make the background transparent in Xcode?

xib, you simply do it in interface builder by selecting the option "Clear Color" for the Background of the view in the Utilities Pane (the pane on the right). "Clear Color" will give the view a completely transparent background.

How do I make a transparent view in SwiftUI?

Any SwiftUI view can be partially or wholly transparent using the opacity() modifier. This accepts a value between 0 (completely invisible) and 1 (fully opaque), just like the alpha property of UIView in UIKit.

How do I present a transparent view controller in Swift?

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values: Background = Clear Color. Drawing = Uncheck the Opaque checkbox.


2 Answers

NSWindow has a property 'opaque' which it is true by default.

The value of this property is true when the window is opaque; otherwise, false.

Just change it to false:

override func viewWillAppear() {
    super.viewWillAppear()
    view.window?.opaque = false
    view.window?.backgroundColor = NSColor(red: 1, green: 0.5, blue: 0.5, alpha: 0.5)
}

Swift 4 update: opaque has been renamed isOpaque

override func viewWillAppear() {
    super.viewWillAppear()
    view.window?.isOpaque = false
    view.window?.backgroundColor = NSColor(red: 1, green: 0.5, blue: 0.5, alpha: 0.5) 
}
like image 64
Leo Dabus Avatar answered Sep 28 '22 05:09

Leo Dabus


Make the window non-opaque, and give it a clear background:

func applicationDidFinishLaunching(aNotification: NSNotification) {
    window.opaque = false
    window.backgroundColor = NSColor.clearColor()
}
like image 40
Paul Patterson Avatar answered Sep 28 '22 06:09

Paul Patterson