因此,我正在尝试为我的QR摄像机视图创建以下图像。
我有一个用于摄像机覆盖的图像(它是屏幕中间的正方形)。
我查看了关于stackoverflow的类似主题,并了解了如何从黑色背景(0.75%透明)中切出相机覆盖图像,使其在中间留有空白,但是在放置时确实存在一些实际问题,而且我无法找出奇怪的地方。
这里是我用来创建背景黑色图像并在中心切出正方形的代码:
// Create a view filling the screen.
let backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
// Set a semi-transparent, black background.
backgroundView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.75)
// Create the initial layer from the view bounds.
let maskLayer = CAShapeLayer()
maskLayer.frame = backgroundView.bounds
maskLayer.fillColor = UIColor.black.cgColor
// Create the path.
let path = UIBezierPath(rect: backgroundView.bounds)
maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
// Append the overlay image to the path so that it is subtracted.
path.append(UIBezierPath(rect: camOverlayImageView.frame))
maskLayer.path = path.cgPath
// Set the mask of the view.
backgroundView.layer.mask = maskLayer
// Add the view so it is visible.
self.view.addSubview(backgroundView)
camOverlayImageView是在情节提要中创建的,并且所有在其上使用的im都是将其垂直和水平居中放置在Superview上的约束,如下所示:
但是,当我这样做时,这就是我在设备上得到的:
[如果有人可能知道这是什么原因或如何解决,将不胜感激,因为我似乎找不到它。
我当然可以手动移动框架并像这样偏移它,但这不是正确的方法:
let overlayFrame = camOverlayImageView.frame
// Append the overlay image to the path so that it is subtracted.
path.append(UIBezierPath(rect: CGRect(
x: overlayFrame.origin.x + 18,
y: overlayFrame.origin.y - 6,
width: overlayFrame.size.width,
height: overlayFrame.size.height))
)
maskLayer.path = path.cgPath
而不是做我以前的工作:
path.append(UIBezierPath(rect: camOverlayImageView.frame))
maskLayer.path = path.cgPath
最有可能...
您创建蒙版还为时过早-在自动布局确定视图大小/放置视图之前。
尝试这样:
class HoleInViewController: UIViewController {
@IBOutlet var camOverlayImageView: UIView!
let backgroundView: UIView = {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = UIColor.black.withAlphaComponent(0.75)
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(backgroundView)
NSLayoutConstraint.activate([
backgroundView.topAnchor.constraint(equalTo: view.topAnchor),
backgroundView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
backgroundView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
backgroundView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Create the initial layer from the view bounds.
let maskLayer = CAShapeLayer()
maskLayer.frame = backgroundView.bounds
maskLayer.fillColor = UIColor.black.cgColor
// Create the path.
let path = UIBezierPath(rect: backgroundView.bounds)
maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
// Append the overlay image to the path so that it is subtracted.
path.append(UIBezierPath(rect: camOverlayImageView.frame))
maskLayer.path = path.cgPath
// Set the mask of the view.
backgroundView.layer.mask = maskLayer
}
}