说明 | |
---|---|
首次发布 | 2019年04月07日 |
最近更新 | 2019年04月07日 |
背景:有些场景,比如展示付款码的时候,需要将屏幕调到最亮以方便商家扫码,在支付完成退出当前页面或者App退到后台时,就需要将屏幕亮度恢复到原来的亮度。
MZBrightnessHelper.h
#import <Foundation/Foundation.h>
@import CoreGraphics;
@interface MZBrightnessHelper : NSObject
/** 逐步设置亮度 */
+ (void)mz_graduallySetBrightness:(CGFloat)value;
/** 逐步恢复亮度 */
+ (void)mz_graduallyResumeBrightness;
@end
MZBrightnessHelper.m
#import "MZBrightnessHelper.h"
#import <UIKit/UIKit.h>
static CGFloat _currentBrightness = 0;
static NSOperationQueue *_queue;
@implementation MZBrightnessHelper
+ (void)initialize {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveDefaultBrightness) name:UIScreenBrightnessDidChangeNotification object:nil];
[self saveDefaultBrightness];
}
+ (void)saveDefaultBrightness {
_currentBrightness = [UIScreen mainScreen].brightness;
}
+ (void)mz_graduallySetBrightness:(CGFloat)value {
if (!_queue) {
_queue = [[NSOperationQueue alloc] init];
_queue.maxConcurrentOperationCount = 1;
}
[_queue cancelAllOperations];
CGFloat brightness = [UIScreen mainScreen].brightness;
CGFloat step = 0.005 * ((value > brightness) ? 1 : -1);
int times = fabs((value - brightness) / 0.005);
for (CGFloat i = 1; i < times + 1; i++) {
[_queue addOperationWithBlock:^{
[NSThread sleepForTimeInterval:1 / 180.0];
[UIScreen mainScreen].brightness = (i == times) ? ((value > brightness) ? value : _currentBrightness) : (brightness + i * step);
}];
}
}
+ (void)mz_graduallyResumeBrightness {
[self mz_graduallySetBrightness:_currentBrightness];
}
@end
使用:注册应用要注册通知UIApplicationWillResignActiveNotification
和UIApplicationDidBecomeActiveNotification
。并在viewWillAppear:
和viewWillDisappear:
做相应设置即可。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
- (void)applicationWillResignActive {
[MZBrightnessHelper mz_graduallyResumeBrightness];
}
- (void)applicationDidBecomeActive {
[MZBrightnessHelper mz_graduallySetBrightness:kScreenBrightness];
}