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:

// TransparentWindow.h
#import <Cocoa/Cocoa.h>
@interface TransparentWindow : NSWindow 


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].

// TransparentWindow.m
#import "TransparentWindow.h"
@implementation TransparentWindow
- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)aStyle backing:(NSBackingStoreType)bufferingType defer:(BOOL)flag
    self = [super initWithContentRect:[[NSScreen mainScreen] frame] styleMask:NSBorderlessWindowMask backing:bufferingType defer:flag];

    if (self)
        [self setBackgroundColor:[NSColor clearColor]];
        [self setOpaque:NO];

    return self;

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.