一、目标
支付宝相信大家都用过,其有一个功能,就是在进入付款
功能中,显示二维码时,屏幕亮度会逐渐增加,而在退出该界面时,屏幕亮度又会逐渐降低,现在我的现在做一个功能。
二、核心属性
@available(iOS 5.0, *)
open var brightness: CGFloat // 0 .. 1.0, where 1.0 is maximum brightness. Only supported by main screen.
这句话能改变屏幕亮度,从iOS 5
开始就可以用了,其取值范围在0.0~1.0之间,1.0是最亮。并且,这句话是全局有效,而不仅仅是设置当前控制器的亮度,也就是说,如果你在某个控制器中改变了屏幕亮度,那么哪怕杀死应用,手机屏幕仍是你设置的亮度,除非用户手动调节亮度值。
三、 屏幕亮度渐变实现
import UIKit
class ViewController: UIViewController {
/// 记录进入该控制器时的亮度,在返回时,改为初始亮度
var brightness: CGFloat = 0
/// 使用定时器,逐步改变屏幕亮度
var timer: Timer?
/// 在界面显示时,逐渐加亮屏幕
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
brightness = UIScreen.main.brightness
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(increaseBrightness), userInfo: nil, repeats: true)
}
/// 界面消失时,恢复屏幕初始亮度
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(decreaseBrightness), userInfo: nil, repeats: true)
}
/// 增加屏幕亮度
@objc private func increaseBrightness() {
if UIScreen.main.brightness > 0.9 {
timer?.invalidate()
timer = nil
return
}
UIScreen.main.brightness += 0.01
}
/// 降低屏幕亮度
@objc private func decreaseBrightness() {
if UIScreen.main.brightness <= brightness {
timer?.invalidate()
timer = nil
return
}
UIScreen.main.brightness -= 0.01
}
}
另外,屏幕的亮度调节只能在真机上看到效果,模拟器上看不到效果!
PS:
// 保存屏幕常亮
UIApplication.shared.isIdleTimerDisabled = true