koogawa blog

iOS、Android、foursquareに関する話題

【Tips】iOSで輝度センサーを使う(Swift対応)

iPhoneの画面輝度(明るさ)が取得・設定できます。

画面輝度=周りの明るさなので、輝度が高ければユーザが明るい場所にいると判断することもできそうです。しかし、中には画面輝度を固定しているユーザもいるので、一概にこの基準が当てはまるとは限りません。

実装方法

画面輝度は次のように取得できます。

Objective-C:

CGFloat brightness = [UIScreen mainScreen].brightness;

Swift:

let brightness = UIScreen.mainScreen().brightness

0.0〜1.0 の値が返ってきます。数値が増えるほど明るくなります。

UIScreenBrightnessDidChangeNotification を監視することで、画面輝度が変わった際に通知を受け取ることができます。

Objective-C:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(screenBrightnessDidChange:)
                                             name:UIScreenBrightnessDidChangeNotification
                                           object:nil];
- (void)screenBrightnessDidChange:(NSNotification *)notification
{
    UIScreen *screen = [notification object];
    self.brightnessLabel.text = [NSString stringWithFormat:@"%f", screen.brightness];
}

Swift:

NSNotificationCenter.defaultCenter().addObserver(self,
                                                 selector: "screenBrightnessDidChange:",
                                                 name: UIScreenBrightnessDidChangeNotification,
                                                 object: nil)
func screenBrightnessDidChange(notification: NSNotification) {
    if let screen = notification.object {
        self.brightnessLabel.text = "".stringByAppendingFormat("%.2f", screen.brightness)
    }
}

取得だけでなく、設定もできます。

Objective-C:

[[UIScreen mainScreen] setBrightness:0.555];

Swift:

UIScreen.mainScreen().brightness = 0.555

サンプルコード

f:id:koogawa:20131117122515p:plain

発表用スライド

注意点

  • iOS 5 以降で使用できます
  • 一部の古い機種では取得できないようです

作れそうなアプリ

  • 明るさ調整アプリ
  • 輝度を利用したゲーム等

私がリリースしている「まりも」アプリでは、光合成判定に使ってます。

まりも

まりも

  • Kosuke Ogawa
  • ゲーム
  • 無料

リンク

参考リンク