How to implement HUD-style window like Address Book's “Show in Large Type”

前端 未结 2 1515
独厮守ぢ
独厮守ぢ 2020-12-07 17:19

Several apps, including the built-in Address Book use a HUD window that is semi-transparent, with large shadowed text. I\'d like to implement a similar window in my Cocoa Ma

相关标签:
2条回答
  • 2020-12-07 17:35

    Thank you for sharing this code. Helped me a lot! You may add the following line...

    [self setBackgroundColor:[NSColor clearColor]];
    

    to the init function of the window. This removes the white corners.

    0 讨论(0)
  • 2020-12-07 17:48

    Here's a sample project that shows how to do it:

    http://github.com/NSGod/BlackBorderlessWindow

    Basically, you need to create a borderless NSWindow subclass. The easiest way to do this is to set your window size and arrangement in the nib file, and then set its class to be your custom subclass. So while it will still look like a normal window in Interface Builder, at runtime it will appear as you need it to.

    @implementation MDBorderlessWindow
    
    - (id)initWithContentRect:(NSRect)contentRect
                styleMask:(NSUInteger)windowStyle
                  backing:(NSBackingStoreType)bufferingType
                    defer:(BOOL)deferCreation {
    
        if (self = [super initWithContentRect:contentRect
                                styleMask:NSBorderlessWindowMask
                                  backing:NSBackingStoreBuffered defer:deferCreation]) {
                [self setAlphaValue:0.75];
                [self setOpaque:NO];
                [self setExcludedFromWindowsMenu:NO];
        }
        return self;
    }
    

    The alpha value will make the window semi-transparent.

    Also, you can create a custom NSView subclass that will draw a round rectangle:

    @implementation MDBlackTransparentView
    
    - (id)initWithFrame:(NSRect)frame {
        if (self = [super initWithFrame:frame]) {
    
        }
        return self;
    }
    
    - (void)drawRect:(NSRect)frame {
        NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:frame
                                        xRadius:6.0 yRadius:6.0];
        [[NSColor blackColor] set];
        [path fill];
    }
    
    @end
    

    Like with the window, you simply set the class of the window's contentView to be your custom NSView subclass. (Use outline view mode and click the disclosure triangle to show the nested NSView inside the icon of the window in the nib file). Again, while the view will look ordinary in Interface Builder, it will look okay at runtime.

    Then just place an NSTextField on top of view and set the text accordingly.

    Note that, in general, borderless windows aren't easy to work with (for example, if you want to be able to drag the window around, you'll need to add that functionality back yourself). Apple has some sample code on how to allow dragging, for instance.

    alt text

    0 讨论(0)
提交回复
热议问题