SpriteKit SKScene add AVCaptureVideoPreviewLayer C

2019-07-10 02:26发布

问题:

I'm attempting to add the AVCaptureVideoPreviewLayer CALayer as the background to my SKScene. I can add the CALayer to the scene, but no matter what attempts at ordering the CALayer is always the top most object.

In the didMoveToView I have the function:

- (void) didMoveToView:(SKView *)view
{
    [self addVideo];

} 

Which calls the addVideo function:

-(void) addVideo {

AVCaptureSession *captureSession = [[AVCaptureSession alloc] init];
captureSession.sessionPreset = AVCaptureSessionPresetHigh;

AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *videoIn = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:nil];

[captureSession addInput:videoIn];

AVCaptureVideoPreviewLayer *avLayer =
[AVCaptureVideoPreviewLayer layerWithSession:captureSession];
avLayer.frame = self.view.bounds;

CGSize landscapeSize;
landscapeSize.width = self.view.bounds.size.height;
landscapeSize.height = self.view.bounds.size.width;


CGRect landscapeRect;
landscapeRect.size = landscapeSize;
landscapeRect.origin = self.view.bounds.origin;

avLayer.frame = landscapeRect;

if(avLayer.connection.supportsVideoOrientation)
{
    avLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
}

[self.scene.view.layer insertSublayer:avLayer atIndex:0];
[self.scene.view.layer setNeedsLayout];


[captureSession startRunning];

}

I've attempted multiple ways to get that AVCaptureVideoPreviewLayer CALayer as the background. Everytime a node is added to the scene it is above this CALayer, any advice?

Attempted the following function:

- (void) sendSublayerToBack:(CALayer *)layer
{
   [layer removeFromSuperlayer];
    [self.view.layer insertSublayer:layer atIndex:0];
}

But still not working....

回答1:

Don't present the layer in the SKView layer - create another UIView and position it in the view hierarchy so it is behind the SKView. Then add the video layer to that UIView.

You will have to make the SKView transparent, though here I'm not sure if this works - if at all it works like it does for cocos2d: set the opaque property to NO and change the backgroundColor property to nil (if not already nil). This should make the SKView transparent.

If none of this works maybe you can find a workaround using SKVideoNode instead.