iOS 手电筒代码和理解

1、首先引入AVFoundation.framework框架

2、.h文件

添加#import <AVFoundation/AVFoundation.h>

@interface LightViewController : UIViewController

{

    BOOL isLightOn;

    AVCaptureDevice *device;

}


@property BOOL isLightOn;

@end

3、.m文件

#import "LightViewController.h"


@interface LightViewController ()


@end


@implementation LightViewController

@synthesize isLightOn;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        self.navigationItem.title = @"手电筒";

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    [btn setFrame:CGRectMake(80, 150, 100, 80)];

    [btn addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn];

    

    //AVCaptureDevice代表抽象的硬件设备

     // 找到一个合适的AVCaptureDevice

    device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    if (![device hasTorch]) {//判断是否有闪光灯

        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"当前设备没有闪光灯,不能提供手电筒功能" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];

        [alter show];

        [alter release];

    }

    

    isLightOn = NO;

    

}


-(void)btnClicked

{

    isLightOn = 1-isLightOn;

    if (isLightOn) {

        [self turnOnLed:YES];

    }else{

        [self turnOffLed:YES];

    }

}


//打开手电筒

-(void) turnOnLed:(bool)update

{

    [device lockForConfiguration:nil];

    [device setTorchMode:AVCaptureTorchModeOn];

    [device unlockForConfiguration];

}


//关闭手电筒

-(void) turnOffLed:(bool)update

{

    [device lockForConfiguration:nil];

    [device setTorchMode: AVCaptureTorchModeOff];

    [device unlockForConfiguration];

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值