Search code examples
iosobjective-cxcodesprite-kitavcapturesession

SpriteKit, how can place live video camera in the background


In the view of main viewcontroller of the game I set the first layer (index 0) with AVCaptureVideoPreviewLayer, and above of the view i placed the SKView with transparent background, (opaque = NO and backgroundColor = clearColor) but it not is right way, how can I do?

// video capture
AVCaptureSession *session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetMedium;
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
[session addInput:input];
AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
previewLayer.opaque = YES;
AVCaptureConnection *previewLayerConnection = previewLayer.connection;
if ([previewLayerConnection isVideoOrientationSupported]) {
    // aggiunge lo sfondo live solo se supportato dal device
    [previewLayerConnection setVideoOrientation:AVCaptureVideoOrientationLandscapeRight | AVCaptureVideoOrientationLandscapeLeft];
    previewLayer.frame = self.view.bounds;
    [self.view.layer insertSublayer:previewLayer atIndex:0];
    [session startRunning];
}

// Create and configure the scene.
GameScene *scene = [GameScene unarchiveFromFile:@"GameScene"];
scene.scaleMode = SKSceneScaleModeAspectFill;

// Present the scene
// @property (nonatomic, weak) IBOutlet SKView *skView;
self.skView.opaque = NO;
self.skView.backgroundColor = [UIColor clearColor];
[self.skView presentScene:scene];

Solution

  • Try setting the allowsTransparency property of your skView to true:

    skView.allowsTransparency = true
    

    See Making a SKScene's background transparent not working... is this a bug? for more info.

    Did this help?