我们如何以编程方式更改iPhone屏幕的亮度?

问题描述 投票:18回答:3

如何使用iPhone SDK以编程方式更改屏幕亮度?

iphone objective-c ios cocoa-touch ios5
3个回答
48
投票
[[UIScreen mainScreen] setBrightness: yourvalue];

需要iOS 5.0或更高版本。 yourvalue是介于0.0和1.0之间的浮点数。


11
投票

更新:对于Swift 3

UIScreen.main.brightness = YourBrightnessValue

这是执行此操作的快速答案

UIScreen.mainScreen().brightness = YourBrightnessValue

YourBrightnessValue是0.01.0之间的一个浮点数


1
投票

我在viewDidLoad / viewWillDisappear中更改屏幕亮度时遇到了一些问题,因此我创建了一个单例类来处理所有操作。我是这样做的:

import Foundation
import UIKit

final class ScreenBrightnessHelper {

    private var timer: Timer?
    private var brightness: CGFloat?
    private var isBrighteningScreen = false
    private var isDarkeningScreen = false

    private init() { }

    static let shared = ScreenBrightnessHelper()

    func brightenDisplay() {
        resetTimer()
        isBrighteningScreen = true
        if #available(iOS 10.0, *), timer == nil {
            brightness = UIScreen.main.brightness
            timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) { (timer) in
                UIScreen.main.brightness = UIScreen.main.brightness + 0.01
                if UIScreen.main.brightness > 0.99 || !self.isBrighteningScreen {
                    self.resetTimer()
                }
            }
        }
        timer?.fire()
    }

    func darkenDisplay() {
        resetTimer()
        isDarkeningScreen = true
        guard let brightness = brightness else {
            return
        }
        if #available(iOS 10.0, *), timer == nil {
            timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) { (timer) in
                UIScreen.main.brightness = UIScreen.main.brightness - 0.01

                if UIScreen.main.brightness < brightness || !self.isDarkeningScreen {
                    self.resetTimer()
                    self.brightness = nil
                }
            }
            timer?.fire()
        }
    }

    private func resetTimer() {
        timer?.invalidate()
        timer = nil
        isBrighteningScreen = false
        isDarkeningScreen = false
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.