-2

所以我正在尝试创建一个 LED 频闪灯,并且我设法为灯制作了一个开/关开关。这是我的代码:

@implementation ViewController
- (void) setTorchOn:(BOOL)isOn
{
AVCaptureDevice* device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[device lockForConfiguration:nil];
[device setTorchMode:isOn ? AVCaptureTorchModeOn : AVCaptureTorchModeOff];
[device unlockForConfiguration];

}

-(IBAction)changedSate:(id)sender {
UISwitch *switchValue = (UISwitch*)sender;

[self setTorchOn:[switchValue isOn]];

我想知道是否有人可以帮助我完成这部分。

4

2 回答 2

0

只需制作一个循环来不断打开和关闭手电筒。循环的类型取决于您希望如何实现。

于 2014-05-20T20:32:48.483 回答
0

我认为您应该使用NSTimer类来反复切换手电筒。还有其他方法,但不要循环使用 sleep() 调用。

// Have an NSTimer* timer and BOOL torchOn and volatile BOOL stopStrobe property in your class...

- (void) startFlashing{
self.timer = [[NSTimer alloc] initWithFireDate:[NSDate timeInvervalSinceNow: 0] interval:0.1 target:self selector:@selector(toggleTorch) userInfo:nil repeats:YES];
}

- (void) toggleTorch{
   if (stopStrobe){
      [self.timer invalidate];
   }
   torchOn = !torchOn
   [self setTorchOn:torchOn];
   }

// Set stopStrobe to YES elsewhere in your program when you want it to stop.

可能是您正在寻找的。

更新:我知道这不是你最初问的,但我知道通过示例学习通常是最好的,所以这里是使用这个的完整示例(未经测试):

@interface ViewController()
@property(nonatomic) BOOL torchOn;
@property(atomic) BOOL stopStrobe;
@end

@implementation ViewController
- (id) init{
self = [super init];
if (self){
self.torchOn = NO;
self.stopStrobe = NO;
}
}

- (void) setTorchOn:(BOOL)isOn
{
AVCaptureDevice* device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[device lockForConfiguration:nil];
[device setTorchMode:isOn ? AVCaptureTorchModeOn : AVCaptureTorchModeOff];
[device unlockForConfiguration];
}

- (void) toggleTorch{
if (stopStrobe){
[self.timer invalidate];
}
self.torchOn = !self.torchOn
[self setTorchOn:self.torchOn];
}

- (void) startFlashing{
self.timer = [[NSTimer alloc] initWithFireDate:[NSDate timeInvervalSinceNow: 0] interval:0.1 target:self selector:@selector(toggleTorch) userInfo:nil repeats:YES];
}

-(IBAction)changedSate:(id)sender {
UISwitch *switchValue = (UISwitch*)sender;
if ([switchValue isOn]{
self.stopStrobe = NO;
[self startFlashing];
}
else{
[self.stopStrobe = YES];
}
}

这将在您打开开关时开始闪烁,并在您关闭开关后停止。

于 2014-05-20T20:45:31.723 回答