6

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?

Shabbir Ahmad
  • 615
  • 7
  • 17
  • 2
    Possible duplicate of [How to set screen brightness with fade animations?](https://stackoverflow.com/questions/15840979/how-to-set-screen-brightness-with-fade-animations) – Anton Malmygin Aug 22 '17 at 11:12
  • Possible duplicate of [iPhone: How can we programmatically change the brightness of the screen?](https://stackoverflow.com/questions/8936999/iphone-how-can-we-programmatically-change-the-brightness-of-the-screen) – Ahmad F Aug 22 '17 at 11:38
  • How would you change it? do you have a slider in your application that should handle it? – Ahmad F Aug 22 '17 at 11:55

2 Answers2

7

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)
        }
    }
}
Juan Sagasti
  • 326
  • 2
  • 5
4

I guess you can set a re-occurring timer like so:

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

And add the update method:

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()
    }
}

Just play around with the timer interval and the brightness decreasing until you find what you are looking for.

Ben10
  • 69
  • 4