xyk blog

最近は iOS 開発の記事が多めです。

プログラムから iPhone 画面の明るさを取得、変更する

検証環境:
Xcode 11.2.1
Swift 5.1.2

iPhone 画面の明るさは UIScreen.main.brightness プロパティから取得できます。
また、UIScreen.main.brightness プロパティに 0.0 から 1.0 の値を設定することで明るさをプログラムから変更できます。
1.0 が最も明るくなります。

brightness - UIScreen | Apple Developer Documentation

以下サンプルコードは特定の画面(UIViewController)でのみ明るさを最大にする例を RxSwift を使って実装しています。
QRコード決済アプリなどでよくやっているやつですね。
その後、その画面を閉じる、またはその画面からアプリをバックグラウンドにしたタイミングで元の明るさに戻しています。

import UIKit
import RxSwift

class QRCodeViewController: UIViewController {

    private let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupScreenBrightness()
        
        // QRコードを表示
        // ...
    }
    
    private func setupScreenBrightness() {
        Observable.merge(
            NotificationCenter.default.rx.notification(UIApplication.didBecomeActiveNotification).map { _ in true },
            NotificationCenter.default.rx.notification(UIApplication.willResignActiveNotification).map { _ in false },
            rx.sentMessage(#selector(viewWillAppear)).map { _ in true },
            rx.sentMessage(#selector(viewWillDisappear)).map { _ in false }
        )
        .subscribe(onNext: { [weak self] active in
            self?.updateScreenBrightness(full: active)
        }).disposed(by: disposeBag)
    }
    
    private var currentBrightness: CGFloat?
    
    private func updateScreenBrightness(full: Bool) {
        if full {
            currentBrightness = UIScreen.main.brightness
            UIScreen.main.brightness = 1.0
        } else {
            if let currentBrightness = currentBrightness {
                UIScreen.main.brightness = currentBrightness
            }
            currentBrightness = nil
        }
    }
}