Exactly matching the background of a selected NSMenuItem

大憨熊 提交于 2019-12-03 21:58:40

Through trial and error I came up with the following code that draws a background almost indistinguishable from the real selected NSMenuItem background in both "Blue" and "Graphite" appearances:

    [[NSColor selectedMenuItemColor] set];
    NSRectFillUsingOperation(dirtyRect, NSCompositeSourceOver);

    if (dirtyRect.size.height > 1) {
        const NSControlTint currentControlTint = [NSColor currentControlTint];

        const CGFloat startingOpacity = (NSBlueControlTint == currentControlTint ? (CGFloat)0.16 : (CGFloat)0.09);
        NSGradient *grad = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithWhite:(CGFloat)1.0 alpha:startingOpacity] endingColor:[NSColor colorWithWhite:(CGFloat)1.0 alpha:(CGFloat)0.0]];

        const CGFloat heightMinus1 = (CGFloat)(dirtyRect.size.height - 1);
        [grad drawFromPoint:NSMakePoint(dirtyRect.origin.x, dirtyRect.origin.y + heightMinus1) toPoint:NSMakePoint(dirtyRect.origin.x, dirtyRect.origin.y + 1) options:0u];

        if (NSBlueControlTint == currentControlTint) {
            [[NSColor colorWithWhite:(CGFloat)1.0 alpha:(CGFloat)0.1] set];
            NSRectFillUsingOperation(NSMakeRect(dirtyRect.origin.x, dirtyRect.origin.y + heightMinus1, dirtyRect.size.width, (CGFloat)1.0), NSCompositeSourceOver);
        }
    }

Here are side-by-side comparisons:

The left halves (80px) of the two images show the real selected NSMenuItem background and the right halves of the two images are the result of the code.

It's not a translucent white gradient. It is drawing a gradient. To do that use NSGradient and NSBezierPath for drawing. Note, you also need to stay in line with what the user has preferred. Gray or Aqua style. This changes the menu highlight. Also, you are going to need to be prepared to do it differently on 10.10

Very differently. In 10.10 you will need to handle a combination of vibrancy Dark mode Light mode Accessibilty settings that further change the colors. Look at that now, and find all the notifications you should observe. but anticipate the colors are still moving targets.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!