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
2
3
4
5
6
7
8
9
// TransparentWindow.h
 
#import <Cocoa/Cocoa.h>
 
@interface TransparentWindow : NSWindow 
{
}
 
@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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 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;
}
 
@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.

Comments 2 comments on this post. Comments are closed.

ardian
Dec 16th, 2007 at 4:36 am

thanks for the hint.

actually i need a full screen window that does not disappeared when i expose or even do space stuff.

your hint give a fullscreen window that cover partially of the workspace. if i switch to another space, it will disappear. do you have any idea on that?

Brian Christensen
Dec 16th, 2007 at 11:26 am

Depending on what you’re trying to do, you have a few options for this. One is to invoke [self setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces], which will cause the window to appear in all of the user’s spaces.

However, if you’re writing a multimedia app or a game, you’ll be better served just using NSView’s enterFullScreenMode: method. You could do something like [[myWindow contentView] enterFullScreenMode:[NSScreen mainScreen] withOptions:nil]. This won’t be transparent though, as it appears this method uses the CGDirectDisplay API to do its job (which puts up a blanking window in the background). (If you use this method, you can skip creating an NSWindow subclass in the first place.)