iOS - 调节控制手电筒亮度
2017-08-28 15:58 菜鸟Alex 阅读(821) 评论(0) 编辑 收藏 举报- 导入框架
#import <AVFoundation/AVFoundation.h>
- 设置属性:
ViewController
中
@interface ViewController ()
/// 获取设备
@property (nonatomic, strong) AVCaptureDevice *device;
/// 手电筒是否开启
@property (nonatomic,assign) BOOL lightOn;
@end
- 获取硬件以及判断手电筒是否可用:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
/**
* hasTorch :返回YES表名手机上有手电筒
*/
if (![_device hasTorch]) {
NSLog(@"手电筒坏了,赶紧换一个iPhone8吧!!!");
return;
}
}
- 设置开关手电筒的一个方法:
clickBtn2:
- (IBAction)clickBtn2:(id)sender {
_lightOn = !_lightOn;
//根据ligthOn状态判断打开还是关闭
// torchLevel
if (_lightOn) {
//开启手电筒
[_device lockForConfiguration:nil];
[_device setTorchMode:AVCaptureTorchModeOn];
// 设置手电筒torchLevel(亮度)数值必须在0~1之间,如果设备过热可能会抛出异常并且不能启动
// 范围 0 - 1 不能是0,应该是(0,1] 左开右闭区间取值,设置数值以前先lock(lockForConfiguration), 设置完毕后一定unlock(unlockForConfiguration)否则崩溃,解决机子过热或者设置导致的崩溃最好的设置方式@try...@catch...@finally捕获异常防止崩溃
[_device setTorchModeOnWithLevel:0.01 error:nil];
[_device unlockForConfiguration];
}else{
//关闭手电筒
[_device lockForConfiguration:nil];
[_device setTorchMode:AVCaptureTorchModeOff];
[_device unlockForConfiguration];
}
}
- 设置手电筒亮度的一个方法:
clickBtn1
/// 设置亮度
- (IBAction)clickBtn1:(id)sender {
[_device lockForConfiguration:nil];
[_device setTorchModeOnWithLevel:1 error:nil];
[_device unlockForConfiguration];
}
注意:
1. 可能由于玩游戏之类原因手机过热导致打开手电筒失败,最终导致崩溃.
2. 设置手电筒的亮度前要lockForConfiguration
3. 设置手电筒完毕后要unlockForConfiguration
4. 最好的办法用@try...@catch...@finally
捕获异常防止崩溃.