服务器之家

服务器之家 > 正文

iOS实现屏幕亮度和闪光灯控制的实例代码

时间:2021-03-17 16:07     来源/作者:呀咪9527

这两天学习了iOS屏幕亮度闪光灯控制,所以,今天添加一点小笔记。

所用涉及框架:AVFoundation框架和ImageIO

读取屏幕亮度:[UIScreen mainScreen].brightness;

设置屏幕亮度:[[UIScreen mainScreen] setBrightness:0.5];

获取环境亮度主要代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
- (void)getTorch {
  AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  AVCaptureDeviceInput *input = [[AVCaptureDeviceInput alloc]initWithDevice:device error:nil];
  AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
  [output setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
  self.session = [[AVCaptureSession alloc]init];
  [self.session setSessionPreset:AVCaptureSessionPresetHigh];
  if ([self.session canAddInput:input]) {
    [self.session addInput:input];
  }
  if ([self.session canAddOutput:output]) {
    [self.session addOutput:output];
  }
  [self.session startRunning];
 
}
 
- (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection {
  CFDictionaryRef metadataDict =CMCopyDictionaryOfAttachments(NULL,sampleBuffer,
  kCMAttachmentMode_ShouldPropagate);
  NSDictionary *metadata = [[NSMutableDictionary alloc] initWithDictionary:
  (__bridgeNSDictionary*)metadataDict];
 
  CFRelease(metadataDict);
  NSDictionary *exifMetadata = [[metadata objectForKey:(NSString*)kCGImagePropertyExifDictionary] mutableCopy];
  float brightnessValue = [[exifMetadata objectForKey:(NSString*)kCGImagePropertyExifBrightnessValue] floatValue];
  NSLog(@"%f",brightnessValue);
  // 根据brightnessValue的值来打开和关闭闪光灯
  AVCaptureDevice*device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  BOOL result = [device hasTorch];// 判断设备是否有闪光灯
  if((brightnessValue <0) && result) {
  // 打开闪光灯
    [device lockForConfiguration:nil];
    [device setTorchMode:AVCaptureTorchModeOn];//开
    [device unlockForConfiguration];
  }else if((brightnessValue >0) && result) {
  // 关闭闪光灯
    [device lockForConfiguration:nil];   
    [device setTorchMode:AVCaptureTorchModeOff];//关
    [device unlockForConfiguration]; 
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部