当视图从纵向更改为横向时,调整带有透明孔的层的位置
Adjust the position of layer with transparent hole when view change from portrait to landscape
我正在使用此代码创建一个带有透明孔的图层
let radius = min(self.view.frame.size.width,self.view.frame.size.height)
print(radius)
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height), cornerRadius: 0)
let circlePath = UIBezierPath(roundedRect: CGRect(x: 0, y: self.view.frame.size.height/2 - radius/2 , width: radius, height: radius), cornerRadius: radius/2)
path.append(circlePath)
path.usesEvenOddFillRule = true
fillLayer.path = path.cgPath
fillLayer.fillRule = kCAFillRuleEvenOdd
fillLayer.fillColor = UIColor.black.cgColor
fillLayer.opacity = 0.5
view.layer.addSublayer(fillLayer)
如果初始视图是图像中显示的纵向或横向,它工作正常
但是,如果视图从纵向变为横向或从横向变为纵向
如图所示图层方向不正确
看来您需要在用户旋转设备时更新路径框架。您正在寻找类似于 .
的答案
如果您需要随着过渡设置动画,请尝试这样的操作:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { context in
// update frames here
}, completion: nil)
}
我正在使用此代码创建一个带有透明孔的图层
let radius = min(self.view.frame.size.width,self.view.frame.size.height)
print(radius)
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height), cornerRadius: 0)
let circlePath = UIBezierPath(roundedRect: CGRect(x: 0, y: self.view.frame.size.height/2 - radius/2 , width: radius, height: radius), cornerRadius: radius/2)
path.append(circlePath)
path.usesEvenOddFillRule = true
fillLayer.path = path.cgPath
fillLayer.fillRule = kCAFillRuleEvenOdd
fillLayer.fillColor = UIColor.black.cgColor
fillLayer.opacity = 0.5
view.layer.addSublayer(fillLayer)
如果初始视图是图像中显示的纵向或横向,它工作正常
但是,如果视图从纵向变为横向或从横向变为纵向
如图所示图层方向不正确
看来您需要在用户旋转设备时更新路径框架。您正在寻找类似于
如果您需要随着过渡设置动画,请尝试这样的操作:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { context in
// update frames here
}, completion: nil)
}