美文网首页工作生活
iOS 闪光灯按钮封装

iOS 闪光灯按钮封装

作者: 辉546 | 来源:发表于2019-07-02 10:26 被阅读0次
#import "SSFlashLightButton.h"
#import <AVFoundation/AVFoundation.h>//调用闪光灯需要导入该框架
@implementation SSFlashLightButton

+ (instancetype)buttonWithType:(UIButtonType)buttonType{
    SSFlashLightButton *flashBtn = [super buttonWithType:buttonType];
    flashBtn.titleLabel.font = [UIFont systemFontOfSize:11];
    flashBtn.backgroundColor = [UIColor purpleColor];
    [flashBtn addTarget:self action:@selector(openFlash:) forControlEvents:UIControlEventTouchUpInside];
    return flashBtn;
}


+ (void)openFlash:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.isSelected == YES) { //打开闪光灯
        AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        NSError *error = nil;
        if ([captureDevice hasTorch]) {
            BOOL locked = [captureDevice lockForConfiguration:&error];
            if (locked) {
                captureDevice.torchMode = AVCaptureTorchModeOn;
                [captureDevice unlockForConfiguration];
            }
        }
    }else{//关闭闪光灯
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch]) {
            [device lockForConfiguration:nil];
            [device setTorchMode: AVCaptureTorchModeOff];
            [device unlockForConfiguration];
        }
    }
}
@end

相关文章

网友评论

    本文标题:iOS 闪光灯按钮封装

    本文链接:https://www.haomeiwen.com/subject/pcaacctx.html