Search code examples
swiftxcodebrightnesscgfloatuiscreen

Adding an animation fade effect when the UIScreen Brightness is changed (Swift)


Just wondering if it is at all possible for the screen brightness to be changed with a fade effect. The screen brightness can yes be changed using UIScreen.mainScreen().brightness = CGFloat(1) but that just immediately changes the current brightness to the variable.

I want to know if you can animate the change of brightness. For example, the current brightness is 0.2 and I want to change it to 0.8 with a fade effect with an increment of 0.1 until it reaches 0.8

Can this be done in swift 2.3?


Solution

  • There are ready made animation methods for UIView and CALayers. But in your case, you want to animate a UIScreen property so you have to do this manually with a timer to gradually change the brightness from 0.1 to 0.8 over a time interval.

        var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
    
        func update() {
            if (UI.mainScreen().brightness >= 0.8) {
               Timer.invalidate(timer)
            }
            else {
            UIScreen.mainScreen().brightness += 0.1
            }
        }
    

    This will change the brightness by 0.1 every 0.4 seconds. When it reaches a value of 0.8 or more it stops. You can make a more gradual or immediate effect by playing with the timerInterval parameter.