//打开手电筒
UIButton flashlightBtn = [UIButton createButtonFrame:CGRectMake(KMainW / 2 - 30, label.bottom + 10, 55, 35) WithTitle:@"轻触照亮" AndWithTitleColor:[UIColor whiteColor] AndWithBackGroundColor:[UIColor clearColor] AndWithTarget:self AndWithSelector:@selector(btnClick:)];
[flashlightBtn setTitle:@"轻触关闭" forState:UIControlStateSelected];
[flashlightBtn setTitleColor:[UIColor colorWithRed:0.11f green:0.54f blue:0.92f alpha:1.00f] forState:UIControlStateSelected];
[flashlightBtn setBackgroundImage:[UIImage imageNamed:@"flashlight_off"] forState:UIControlStateNormal];
[flashlightBtn setBackgroundImage:[UIImage imageNamed:@"flashlight_on"] forState:UIControlStateSelected];
flashlightBtn.titleLabel.font = [UIFont systemFontOfSize:13];
// button标题的偏移量
[flashlightBtn setTitleEdgeInsets:UIEdgeInsetsMake(flashlightBtn.imageView.frame.size.height+80, -flashlightBtn.imageView.bounds.size.width, 0,0)];
// button图片的偏移量
[flashlightBtn setImageEdgeInsets:UIEdgeInsetsMake(0, flashlightBtn.titleLabel.frame.size.width/2, flashlightBtn.titleLabel.frame.size.height+5, -flashlightBtn.titleLabel.frame.size.width/2)];
[cover addSubview:flashlightBtn];
}
-(void)btnClick:(UIButton)btn
{
btn.selected = !btn.selected;
[self turnTorchOn:btn.selected];
}
//打开手电筒
-(void)turnTorchOn: (bool) on
{
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass !=nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){ // 判断是否有闪光灯
// 请求独占访问硬件设备
[device lockForConfiguration:nil];
if (on) {
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
} else {
[device setTorchMode:AVCaptureTorchModeOff];
[device setFlashMode:AVCaptureFlashModeOff];
}
// 请求解除独占访问硬件设备
[device unlockForConfiguration];
}else{
NSLog(@"初始化失败");
}
}else{
NSLog(@"没有闪光设备");
}
}
网友评论