How to set screen brightness with fade animations?

后端 未结 7 1600
梦如初夏
梦如初夏 2021-01-02 11:32

Is it possible to animate the screen brightness change on iOS 5.1+? I am using [UIScreen mainScreen] setBrightness:(float)] but I think that the abrupt change i

7条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-02 12:09

    I ran into issues with the accepted answer when attempting to animate to another value with a previous animation in progress. This solution cancels an in-progress animation and animates to the new value:

    extension UIScreen {
    
        func setBrightness(_ value: CGFloat, animated: Bool) {
            if animated {
                _brightnessQueue.cancelAllOperations()
                let step: CGFloat = 0.04 * ((value > brightness) ? 1 : -1)
                _brightnessQueue.add(operations: stride(from: brightness, through: value, by: step).map({ [weak self] value -> Operation in
                    let blockOperation = BlockOperation()
                    unowned let _unownedOperation = blockOperation
                    blockOperation.addExecutionBlock({
                        if !_unownedOperation.isCancelled {
                            Thread.sleep(forTimeInterval: 1 / 60.0)
                            self?.brightness = value
                        }
                    })
                    return blockOperation
                }))
            } else {
                brightness = value
            }
        }
    
    }
    
    private let _brightnessQueue: OperationQueue = {
        let queue = OperationQueue()
        queue.maxConcurrentOperationCount = 1
        return queue
    }()
    

提交回复
热议问题