Search code examples
macosgraphicsquartz-2d

Can the background for a mac app be transparent?


I'm using quartz2d to make my first mac app and I was wondering if it's possible to make the background transparent. Meaning that if all the app did was set the background transparent then when it ran you would see nothing except the apps behind it.

I have a feeling this isn't possible, but I thought I'd ask anyway.


Solution

  • Actually, it is possible.

    And you can even make the app's fully transparent window be click-through. See: Drawing a custom window on Mac OS X.

    Constructing a transparent window

    Making a custom window starts with a transparent window. I will use a custom NSWindow subclass named RoundWindow. The constructor for this subclass looks like this:

    - (id)initWithContentRect:(NSRect)contentRect
        styleMask:(NSUInteger)windowStyle
        backing:(NSBackingStoreType)bufferingType
        defer:(BOOL)deferCreation
    {
        self = [super
            initWithContentRect:contentRect
            styleMask:NSBorderlessWindowMask
            backing:bufferingType
            defer:deferCreation];
        if (self)
        {
            [self setOpaque:NO];
            [self setBackgroundColor:[NSColor clearColor]];
        }
        return self;
    }
    

    The three changes made to the window by this constructor are fairly obvious:

    • NSBorderlessWindowMask (a window without standard window framing)
    • setOpaque:NO (so that any part of the window can be transparent)
    • setBackgroundColor:[NSColor clearColor] (if we do nothing else, this will paint the window transparent)

    The result is a transparent, rectangular window. This method can be invoked directly (if creating a window in code). It will also be invoked by the NIB loader when loading the window from a NIB.

    Since this window uses the NSBorderlessWindowMask style, we must override the canBecomeKeyWindow and canBecomeMainWindow methods to return YES. These overrides will allow the window to be the keyboard focus and primary application window respectively.

    Source: Drawing a custom window on Mac OS X.