我是iOS应用程序开发的新手,我试图改变屏幕亮度,但它变化得相当突然。有没有一种方法可以平滑地动画显示屏幕亮度?
使用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)
}
}
}
我猜你可以这样设置一个重复定时器:
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()
}
}
只需玩弄计时器间隔和亮度降低,直到找到您要寻找的内容。