我为相机屏幕创建了一个蒙版视图,该蒙版视图模糊了除了中间的一个小矩形之外的所有内容。在不同屏幕尺寸上进行测试时出现问题。我正在11 Pro和8 Pro上进行测试。如果我的情节提要视图选择了正确的设备,则该设备上的约束看起来很好。但是,如果我在不更改情节提要的情况下切换电话,那是不正确的。我正在以编程方式创建蒙版视图。任何帮助将不胜感激!
func setupBlur() {
if !UIAccessibility.isReduceTransparencyEnabled {
blurView.backgroundColor = .clear
let blurEffect = UIBlurEffect(style: .dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = blurView.bounds
blurEffectView.translatesAutoresizingMaskIntoConstraints = false
blurEffectView.addConstraints(blurView.constraints)
blurView.addSubview(blurEffectView)
let maskView = UIView(frame: blurView.bounds)
maskView.translatesAutoresizingMaskIntoConstraints = false
maskView.addConstraints(blurView.constraints)
maskView.backgroundColor = .clear
let outerbezierPath = UIBezierPath.init(rect: blurView.bounds)
let croppedOriginX = (blurView.bounds.width / 2) - (captureView.bounds.width / 2)
let croppedOriginY = (blurView.bounds.height / 2) - (captureView.bounds.height / 2)
let frame = CGRect(x: croppedOriginX, y: croppedOriginY, width: captureView.bounds.width, height: captureView.bounds.height)
let innerRectPath = UIBezierPath.init(rect: frame)
outerbezierPath.append(innerRectPath)
outerbezierPath.usesEvenOddFillRule = true
let fillLayer = CAShapeLayer()
fillLayer.fillRule = kCAFillRuleEvenOdd
fillLayer.fillColor = UIColor.green.cgColor // any opaque color would work
fillLayer.path = outerbezierPath.cgPath
maskView.layer.addSublayer(fillLayer)
blurView.mask = maskView;
}
}
之所以发生这种情况,是因为当您从setupBlur()
调用viewDidLoad
时,blurView.bounds
的值最初是您正在处理的stroyboard
的值,并且您正在使用这些界限来设置blurEffectView.frame
根据设备的屏幕进行调整。
这不是最佳解决方案,但我希望它能解决您的问题。
尝试一下:
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.setupBlur()
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.setupBlur()
}