Рисование прямоугольника поверх слоя AVCaptureVideoPreviewLayer, возможно? - PullRequest
6 голосов
/ 14 декабря 2010

Я уже несколько дней бьюсь об этом.

Я хочу нарисовать прямоугольник поверх CALayer (AVCaptureVideoPreviewLayer), который просто является видеопотоком с камеры на iPhone4.

вот часть моей настройки;

    //(in function for initialization)

        -(void)initDevices {
           AVCaptureDeviceInput *captureInput = [AVCaptureDeviceInput                   deviceInputWithDevice:[AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo] error:nil];

           AVCaptureVideoDataOutput *captureOutput = [[AVCaptureVideoDataOutput alloc] init];
           captureOutput.alwaysDiscardsLateVideoFrames = YES; 
           captureOutput.minFrameDuration = CMTimeMake(1, 30);
           dispatch_queue_t queue;
           queue = dispatch_queue_create("cameraQueue", NULL);
           [captureOutput setSampleBufferDelegate:self queue:queue];
           dispatch_release(queue);

           NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey; 
           NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA]; 
           NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:value forKey:key]; 
           [captureOutput setVideoSettings:videoSettings]; 
           self.captureSession = [[AVCaptureSession alloc] init];
           [self.captureSession addInput:captureInput];
           [self.captureSession addOutput:captureOutput];
           [self.captureSession setSessionPreset:AVCaptureSessionPresetHigh];   
           self.prevLayer = [AVCaptureVideoPreviewLayer layerWithSession: self.captureSession];
           self.prevLayer.frame = CGRectMake(0, 0, 400, 400); 
           self.prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
           self.prevLayer.delegate = self;
           [self.view.layer addSublayer: self.prevLayer];
    }

    - (void)captureOutput:(AVCaptureOutput *)captureOutput 
      didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer 
      fromConnection:(AVCaptureConnection *)connection { 

       [self performSelectorOnMainThread:@selector(drawme) withObject:nil waitUntilDone:YES];
    }

    - (void)drawme {
 [self.prevLayer setNeedsDisplay];
    }

    //delegate function that draws to a CALayer
    - (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)ctx {
     NSLog(@"hello layer!");
     CGContextSetRGBFillColor (ctx, 1, 0, 0, 1);
            CGContextFillRect (ctx, CGRectMake (0, 0, 200, 100 ));
    }

Это вообще возможно? Исходя из моего текущего кода, я получаю печать "привет слой", но у канала камеры нет заполненного прямоугольника.

Любая помощь будет потрясающей. :)

Ответы [ 2 ]

1 голос
/ 20 августа 2015

Я думаю, вы должны добавить еще один слой в AVCaptureVideoPreviewLayer, и я изменю пример кода для вас. Вы можете попробовать это.

    //(in function for initialization)

    -(void)initDevices {
       AVCaptureDeviceInput *captureInput = [AVCaptureDeviceInput                   deviceInputWithDevice:[AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo] error:nil];

       AVCaptureVideoDataOutput *captureOutput = [[AVCaptureVideoDataOutput alloc] init];
       captureOutput.alwaysDiscardsLateVideoFrames = YES; 
       captureOutput.minFrameDuration = CMTimeMake(1, 30);
       dispatch_queue_t queue;
       queue = dispatch_queue_create("cameraQueue", NULL);
       [captureOutput setSampleBufferDelegate:self queue:queue];
       dispatch_release(queue);

       NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey; 
       NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA]; 
       NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:value forKey:key]; 
       [captureOutput setVideoSettings:videoSettings]; 
       self.captureSession = [[AVCaptureSession alloc] init];
       [self.captureSession addInput:captureInput];
       [self.captureSession addOutput:captureOutput];
       [self.captureSession setSessionPreset:AVCaptureSessionPresetHigh];   
       self.prevLayer = [AVCaptureVideoPreviewLayer layerWithSession: self.captureSession];
       self.prevLayer.frame = CGRectMake(0, 0, 400, 400); 
       self.prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
       [self.view.layer addSublayer:self.prevLayer];

       self.drawLayer = [CAShapeLayer layer];
       CGRect parentBox = [self.captureVideoPreviewLayer frame];
       [self.drawLayer setFrame:parentBox];
       [self.drawLayer setDelegate:self];
       [self.drawLayer setNeedsDisplay];
       [self.captureVideoPreviewLayer addSublayer:self.drawLayer];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput 
    didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer 
    fromConnection:(AVCaptureConnection *)connection { 

    [self performSelectorOnMainThread:@selector(drawme) withObject:nil waitUntilDone:YES];
}

- (void)drawme {
    [self.drawLayer setNeedsDisplay];
}

//delegate function that draws to a CALayer
- (void)drawLayer:(CALayer*)layer inContext:(CGContextRef)ctx {
    NSLog(@"hello layer!");
    CGContextSetRGBFillColor (ctx, 1, 0, 0, 1);
    CGContextFillRect (ctx, CGRectMake (0, 0, 200, 100 ));
}
0 голосов
/ 05 августа 2017

Или вы можете вставить только изображение - вы можете использовать AVCaptureVideoPreviewLayer для захвата видео, очевидно, и создать еще один CALayer () и использовать layer.insertSublayer (..., выше: ...), чтобы вставить свой «пользовательский» слой выше слой видео, и под обычаем я подразумеваю просто еще один CALayer с пусть скажем

layer.contents = spinner.cgImage

Вот немного более подробные инструкции для Swift

...