iOS-手电筒照明

本文介绍了一种在iOS应用中实现手电筒功能的方法,通过初始化相机设备并利用AVFoundation框架来控制手电筒的开关状态。文章提供了完整的代码示例,包括如何通过按钮点击事件来切换手电筒的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

打开手电筒照明的思路:初始化相机设备 -> 点击按钮 -> 改变照明状态 -> 根据状态打开或关闭手电筒

#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.youkuaiyun.com/qq_36557133/article/details/81626395

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值