以编程方式在AVCaptureVideoPreviewLayer上添加UIButton

时间:2017-08-03 13:42:02

标签: ios iphone swift overlay avcapture

我正在尝试在AVCaptureVideoPreviewLayer

之上创建叠加层

我尝试了以下操作,但结果不符合我的预期,因为按钮的标题不可见:

let previewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.avCaptureSession)
previewLayer.frame = self.view.layer.frame
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.view.layer.addSublayer(previewLayer)



//Add Button
let captureButton = UIButton(frame: CGRectMake(0, 0, 100 , 100))
captureButton.backgroundColor = UIColor.grayColor()
captureButton.setTitle("Capture", forState: .Normal)
captureButton.setTitleColor(UIColor.redColor(), forState: .Normal)
captureButton.addTarget(self, action: "actionCapture:", forControlEvents: .TouchDragInside)

previewLayer.addSublayer(captureButton.layer)

以下是当前状态的屏幕截图:

screenshot of the current state

1 个答案:

答案 0 :(得分:5)

您应该将previewLayer添加到单独的视图子图层中。这样,您就可以轻松地在主视图上方添加其他子视图。

let previewView = UIView(frame: view.frame)
view.addSubview(previewView)

previewView.layer.addSublayer(previewLayer)

[...]

view.addSubview(captureButton)