iOS-手電筒照明

打開手電筒照明的思路:初始化相機設備 -> 點擊按鈕 -> 改變照明狀態 -> 根據狀態打開或關閉手電筒

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
 
@interface ViewController ()
 
@property (nonatomic, strong) AVCaptureDevice *device;//捕獲設備
 
@end
 
@implementation ViewController
{
    BOOL device_open;//判斷照明狀態
    UIButton *scanBtn;
}
 
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
  
    //創建按鈕
    [self creatControl];
}
 
- (void)creatControl {
 
    //初始化相機設備
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
 
    //照明按鈕
    scanBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    scanBtn.frame = CGRectMake(100, 100, 100, 44);
    [scanBtn setTitle:@"打開照明" forState:UIControlStateNormal];
    [scanBtn addTarget:self action:@selector(scanBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn];
    
}
 
-(void)scanBtnOnClick {  
    
    NSLog(@"%@",device_open?@"YES":@"NO");
    
    //改變狀態
    device_open = !device_open;
    
    //判斷設備是否有閃關燈
    if (![self.device hasTorch]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                       message:@"當前設備沒有閃關燈,無法開啓照明功能"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"確認"
                                                             style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction * _Nonnull action) {
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"
                                                               style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:sureAction];
        [alert addAction:cancelAction];
        
        [self presentViewController:alert animated:YES completion:nil];
    }
    
    [self.device lockForConfiguration:nil];
    
    //根據狀態,打開或關閉照明
    if (device_open) {
        [self.device setTorchMode:AVCaptureTorchModeOn];
        [scanBtn setTitle:@"關閉照明" forState:UIControlStateNormal];
    }
    else {
        [self.device setTorchMode:AVCaptureTorchModeOff];
        [scanBtn setTitle:@"打開照明" forState:UIControlStateNormal];
    }
}
 
@end


原文鏈接:https://blog.csdn.net/qq_36557133/article/details/81626395

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章