获取显示亮度

Get Display Brightness

既然 CGDisplayIOServicePort 已被弃用,是否有办法在 OS X 10.9+ 中获得显示亮度?

经过一些搜索和摆弄后,这里有一个 "future proof" 获取显示器亮度的方法,它不使用 OS X 10.9 中弃用的 CGDisplayIOServicePort .

- (float)getDisplayBrightness
{
    float brightness = 1.0f;
    io_iterator_t iterator;
    kern_return_t result = 
        IOServiceGetMatchingServices(kIOMasterPortDefault,
            IOServiceMatching("IODisplayConnect"),
            &iterator);

    // If we were successful
    if (result == kIOReturnSuccess)
    {
        io_object_t service;

        while ((service = IOIteratorNext(iterator)))
        {
            IODisplayGetFloatParameter(service, 
                kNilOptions, 
                CFSTR(kIODisplayBrightnessKey), 
                &brightness);

            // Let the object go
            IOObjectRelease(service);
        }
    }

    return brightness;
}

如果您使用的是 swift,则以下内容应该有效:

func getDisplayBrightness() -> Float {

    var brightness: Float = 1.0
    var service: io_object_t = 1
    var iterator: io_iterator_t = 0
    let result: kern_return_t = IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"), &iterator)

    if result == kIOReturnSuccess {

        while service != 0 {
            service = IOIteratorNext(iterator)
            IODisplayGetFloatParameter(service, 0, kIODisplayBrightnessKey as CFString, &brightness)
            IOObjectRelease(service)
        }
    }
    return brightness
}