如何在Swift 3中平滑地改变屏幕亮度?

问题描述 投票:2回答:2

我是iOS应用程序开发的新手,我正在尝试改变屏幕亮度,但它突然发生。有没有办法平滑地为屏幕亮度设置动画?

ios iphone swift
2个回答
3
投票

我想你可以像这样设置一个重现计时器:

var timer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)

并添加更新方法:

func update() {
    UIScreen.main.brightness = UIScreen.main.brightness - CGFloat(0.1)
    if UIScreen.main.brightness == CGFloat(0.5) { // or any brightness you want.
        timer.invalidate()
    }
}

只需使用定时器间隔和亮度降低,直到找到您要找的内容。


3
投票

而不是计时器,Swift扩展:

  extension UIScreen {

    private static let step: CGFloat = 0.1

    static func animateBrightness(to value: CGFloat) {
        guard fabs(UIScreen.main.brightness - value) > step else { return }

        let delta = UIScreen.main.brightness > value ? -step : step

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            UIScreen.main.brightness += delta
            animateBrightness(to: value)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.