我有创建路径并设置为蒙版的方法,但它显示为视图的1/4。我还需要设置其他内容吗?看起来像视网膜问题或坐标问题,但不确定是哪一个。
func layoutZigZag(bounds: CGRect) -> CALayer {
let maskLayer = CAShapeLayer()
maskLayer.bounds = bounds
let path = UIBezierPath()
let width = bounds.size.width
let height = bounds.size.height
let topRight = CGPoint(x: width , y: height)
let topLeft = CGPoint(x: 0 , y: height)
let bottomRight = CGPoint(x: width , y: 0)
let bottomLeft = CGPoint(x: 0 , y: 0)
let zigzagHeight: CGFloat = 10
let numberOfZigZag = Int(floor(width / 23.0))
let zigzagWidth = width / CGFloat(numberOfZigZag)
path.move(to: topLeft)
path.addLine(to: bottomLeft)
// zigzag
var currentX = bottomLeft.x
var currentY = bottomLeft.y
for i in 0..<numberOfZigZag {
let upper = CGPoint(x: currentX + zigzagWidth / 2, y: currentY + zigzagHeight)
let lower = CGPoint(x: currentX + zigzagWidth, y: currentY)
path.addLine(to: upper)
path.addLine(to: lower)
currentX += zigzagWidth
}
path.addLine(to: topRight)
path.close()
maskLayer.path = path.cgPath
return maskLayer
}
and
let rect = CGRect(x: 0, y: 0, width: 320, height: 400)
let view = UIView(frame: rect)
view.backgroundColor = UIColor.red
let zigzag = layoutZigZag(bounds: rect)
view.layer.mask = zigzag
路径看起来正确
结果是视图的1/4
答案 0 :(得分:1)
将maskLayer.bounds = bounds
更改为maskLayer.frame = bounds
更新:
颠倒是因为UI和CG之间存在差异,我们在UIBezierPath中创建路径并将该路径转换为CGPath(maskLayer.path = path.cgPath
)。首先,我们必须知道差异,其中CGPath is Quartz 2D和来源位于左下角,而UIBezierPath is UIKit 来源位于左上角。根据你的代码,当我们转换为CGPath(左下角的原点)时,应用的坐标是左上角即UIBezierPath,它变得颠倒了。所以更改下面的代码以获得所需的效果。
let topRight = CGPoint(x: width , y: 0)
let topLeft = CGPoint(x: 0 , y: 0)
let bottomLeft = CGPoint(x: 0 , y: (height - zigzagHeight))
Quartz 2D坐标系
UIBezierPath坐标系