作为面具的CAShaperLayer仅显示UIView

时间:2016-11-07 12:12:50

标签: ios swift mask cashapelayer

我尝试让UIView显示锯齿形底边。像http://www.shutterstock.com/pic-373176370/stock-vector-receipt-vector-icon-invoice-flat-illustration-cheque-shadow-bill-with-total-cost-amount-and-dollar-symbol-abstract-text-receipt-paper-isolated-on-green.html?src=zMGBKj_5etMCcRB3cKmCoA-1-2

这样的东西

我有创建路径并设置为蒙版的方法,但它显示为视图的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

路径看起来正确

Path look correct

结果是视图的1/4

Result

1 个答案:

答案 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坐标系

enter image description here

UIBezierPath坐标系

enter image description here