3

我想在我的 UIImagePickerController 中添加一个叠加层,但我只需要它来覆盖相机预览,而不是顶部或底部的相机控件。我找不到任何方法来做到这一点,因为每个设备上的顶部/底部控件高度都不同。我以前在其他应用程序上看到过它。任何指导表示赞赏。

imagePicker.sourceType = .camera
            
let overlay = UIView()
overlay.backgroundColor = UIColor(white: 1, alpha: 0.5)

imagePicker.cameraOverlayView!.addSubview(overlay)
// This is using a UIView extension to constrain my views. It's as simple as it looks.
overlay.anchor(top: imagePicker.cameraOverlayView!.topAnchor, left: imagePicker.cameraOverlayView!.leftAnchor, bottom: imagePicker.cameraOverlayView!.bottomAnchor, right: imagePicker.cameraOverlayView!.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 100, height: 100)
        
self.present(imagePicker, animated: true, completion: nil)

我希望这个半透明的 UIView 只填充红色区域。我将框架创建为 3:4 没有问题,但它不会在 Y 轴上正确定位。imagePicker.cameraOverlayView!.centerYAnchor与设备的 centerYAnchor 相同。

UIImagePickerController

4

1 回答 1

1

也许不是最好的解决方案。使用视图调试器,您可以检查视图层次结构。现在将视图添加到孩子中camera view port controller

imagePicker = CustomPicker()
imagePicker.sourceType = .camera
present(imagePicker, animated: true, completion: nil)


class CustomPicker: UIImagePickerController {
    let overlay = UIView()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let camController = children.first?.children.first?.children.first, overlay.superview == nil {
            overlay.backgroundColor = UIColor(white: 1, alpha: 0.5)
            camController.view.addSubview(overlay)
            overlay.addPinConstraints(top: 0, left: 0, bottom: 0, right: 0)
        }
    }
}

extension UIView {
    func addPinConstraints(top: CGFloat? = nil, left: CGFloat? = nil, bottom: CGFloat? = nil, right: CGFloat? = nil) {
        guard let parent = superview else { return }
        translatesAutoresizingMaskIntoConstraints = false
        if let left = left {
            leadingAnchor.constraint(equalTo: parent.leadingAnchor, constant: left).isActive = true
        }
        if let right = right {
            trailingAnchor.constraint(equalTo: parent.trailingAnchor, constant: -right).isActive = true
        }
        if let top = top {
            topAnchor.constraint(equalTo: parent.topAnchor, constant: top).isActive = true
        }
        if let bottom = bottom {
            bottomAnchor.constraint(equalTo: parent.bottomAnchor, constant: -bottom).isActive = true
        }
    }
}

视图检查器的屏幕截图,这里的 child -> child -> child 是相机视图端口 在此处输入图像描述

于 2022-01-27T19:45:57.907 回答