Create a transparent fullscreen view
December 15, 2007
The question of how to create a transparent fullscreen view came up on the cocoa-dev list recently. As it turns out, it is fairly trivial to implement.
The custom window subclass
Create the following header file:
1 // TransparentWindow.h
2
3 #import <Cocoa/Cocoa.h>
4
5 @interface TransparentWindow : NSWindow
6 {
7 }
8
9 @end
In the implementation all we need to do to make the window transparent is specify a NSBorderlessWindowMask and set the background color to [NSColor clearColor].
1 // TransparentWindow.m
2
3 #import "TransparentWindow.h"
4
5 @implementation TransparentWindow
6
7 - (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)aStyle backing:(NSBackingStoreType)bufferingType defer:(BOOL)flag
8 {
9 self = [super initWithContentRect:[[NSScreen mainScreen] frame] styleMask:NSBorderlessWindowMask backing:bufferingType defer:flag];
10
11 if (self)
12 {
13 [self setBackgroundColor:[NSColor clearColor]];
14 [self setOpaque:NO];
15 }
16
17 return self;
18 }
19
20 @end
Using the window class
To use this window you can either instantiate it programmatically or set it as the custom window class in your NIB file (I am using the latter method myself in a current project).
If you need a semi-transparent window, you can substitute something like [NSColor colorWithCalibratedWhite:1.0 alpha:0.5] for the color object in line 13.
And, depending on what you are doing, you may want your window to appear above the menubar. To do so, add [self setLevel:NSMainMenuWindowLevel + 1]; after line 14.