Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work around transparent system colors when drawing with Core Animation layers on Mojave?

With dark mode in macOS 10.14 Mojave, most system colors are semi-transparent. That is to match control colors with the window background, which in turn is slightly tinted to match the desktop picture.

Now when building a view with overlapping CoreAnimation layers, things get messed up. Example:

custom slider control

This is a custom slider built with CALayers. The vertical track is a layer beneath the knob layer. Here's how I set the colors:

- (void)updateColors // Called from updateLayer()
{
    self.tickmarkLayer.strokeColor = [NSColor tertiaryLabelColor].CGColor;
    self.tickmarkLayer.lineWidth = 1.0;

    self.trackLayer.backgroundColor = [NSColor controlBackgroundColor].CGColor;
    self.trackLayer.borderColor = [NSColor tertiaryLabelColor].CGColor;
    self.trackLayer.borderWidth = 1.0;

    self.sliderLayer.backgroundColor = [NSColor controlColor].CGColor;
}

Of course, I don't want the knob to be transparent, i. e. the track layer should not shine through. How can I work around this while preserving the dynamic tint?

Ideally, one could access the the "effective" system colors with the current tint and no transparency. But I didn't find any API to do so.

A similar problem occurs when applying a shadow to layers that have transparent (system) colors.

Thanks!

like image 815
C. S. Hammersmith Avatar asked Mar 17 '19 10:03

C. S. Hammersmith


1 Answers

Does NSColor's colorWithAlphaComponent: do the trick for you?

https://developer.apple.com/documentation/appkit/nscolor/1526906-colorwithalphacomponent?language=objc

i.e.

self.sliderLayer.backgroundColor = [[NSColor controlColor] colorWithAlphaComponent:1.0f].CGColor;

It looks like darkMode sets the alpha component of control color to: 0.247059

like image 158
R4N Avatar answered Sep 21 '22 03:09

R4N