CALayer in SwiftUI: add CALayer circleLayer to view Camera layer but not show it on the screen

42 Views Asked by At

I am working on an object detection application in SwiftUI. I have a problem: I added circleLayer as ship to the view Camera but cannot show it on the screen

You can also see here that I configure the Session the tour for the camera

{

func configureSession() {
    if setupResult != .success {
        return
    }session.beginConfiguration()

    session.sessionPreset = .vga640x480
    
    // Add video input.
    do {
        var defaultVideoDevice: AVCaptureDevice?
        
        if let backCameraDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) {
            // If a rear dual camera is not available, default to the rear wide angle camera.
            defaultVideoDevice = backCameraDevice
        } else if let frontCameraDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front) {
            // If the rear wide angle camera isn't available, default to the front wide angle camera.
            defaultVideoDevice = frontCameraDevice
        }
        
        guard let videoDevice = defaultVideoDevice else {
            print("Default video device is unavailable.")
            setupResult = .configurationFailed
            session.commitConfiguration()
            return
        }
        
        let videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice)
        
        if session.canAddInput(videoDeviceInput) {
            session.addInput(videoDeviceInput)
            self.videoDeviceInput = videoDeviceInput
            
        } else {
            print("Couldn't add video device input to the session.")
            setupResult = .configurationFailed
            session.commitConfiguration()
            return
        }
    } catch {
        print("Couldn't create video device input: \(error)")
        setupResult = .configurationFailed
        session.commitConfiguration()
        return
    }
    
    if session.canAddOutput(videoDataOutput) {
        session.addOutput(videoDataOutput)
        // Add a video data output
        videoDataOutput.alwaysDiscardsLateVideoFrames = true
        videoDataOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange)]
       videoDataOutput.setSampleBufferDelegate(self, queue: videoDataOutputQueue)
    } else {
        print("Could not add video data output to the session")
        session.commitConfiguration()
        return
    }
    
    
    let captureConnection = videoDataOutput.connection(with: .video)
    // Always process the frames
    captureConnection?.isEnabled = true
    do {
        try  videoDevice!.lockForConfiguration()
        let dimensions = CMVideoFormatDescriptionGetDimensions((videoDevice?.activeFormat.formatDescription)!)
        bufferSize.width = CGFloat(dimensions.width)
        bufferSize.height = CGFloat(dimensions.height)
        videoDevice!.unlockForConfiguration()

    } catch {
        print(error)
    }
   
    session.commitConfiguration()
    
    self.isConfigured = true
    
    DispatchQueue.global(qos: .userInitiated).async { [weak self] in
               self?.session.startRunning()
    
}

// here i try to add CL Layer

func configure() {
    configureSession()

    print("sublayers before add \(self.view.layer.sublayers!.count)")   // =1 

    let circleLayer = CALayer()
    circleLayer.name="Younus"

    circleLayer.frame = CGRect(x: 200, y: 200, width: 400, height: 400)
    circleLayer.backgroundColor = UIColor.green.cgColor
      
    self.view.layer.addSublayer(circleLayer)

    print("sublayers before add \(self.view.layer.sublayers!.count)")==2
    
 
    
    for sublayer in view.layer.sublayers! {
        print(sublayer.name)
    }

}
}

Here the UIview

struct CameraPreview: UIViewRepresentable {
class VideoPreviewView: UIView {
    override class var layerClass: AnyClass {
         AVCaptureVideoPreviewLayer.self
    }
    
    var videoPreviewLayer: AVCaptureVideoPreviewLayer {
        return layer as! AVCaptureVideoPreviewLayer
    }
}

let session: AVCaptureSession

func makeUIView(context: Context) -> VideoPreviewView {
    let view = VideoPreviewView()
    view.backgroundColor = .black
    view.videoPreviewLayer.cornerRadius = 0
    view.videoPreviewLayer.session = session
    view.videoPreviewLayer.connection?.videoOrientation = .portrait

    return view
}

func updateUIView(_ uiView: VideoPreviewView, context: Context) {
    
    }
}

struct CameraPreview_Previews: PreviewProvider {
    static var previews: some View {
        CameraPreview(session: AVCaptureSession())
            .frame(height: 20)
    }
}

Can you explain to me why adding another Layer does not work and how to solve it?

0

There are 0 best solutions below