Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to smoothly change screen brightness in Swift 3?

Tags:

ios

swift

iphone

I'm new to iOS app development and I'm trying to change the screen brightness but it happens pretty abruptly. Is there a way to animate the screen brightness smoothly?

like image 277
August van de Ven Avatar asked Dec 14 '22 21:12

August van de Ven


1 Answers

Instead of a timer, a Swift extension:

  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)
        }
    }
}
like image 197
Juan Sagasti Avatar answered Dec 16 '22 11:12

Juan Sagasti