CAShapeLayer凹槽路径

时间:2017-11-18 10:07:01

标签: ios swift cashapelayer

我想制作一个白色的彩色视图,其中有一个三角形指针,如下所示:

enter image description here

如上图所示,目标是在white视图中嵌入“圆形凹槽”

    let pointerRadius:CGFloat = 4
    pointerLayer = CAShapeLayer()
    pointerLayer.path = pointerPathForContentSize(contentSize: bounds.size).cgPath
    pointerLayer.lineJoin = kCALineJoinRound
    pointerLayer.lineWidth = 2*pointerRadius
    pointerLayer.fillColor = UIColor.white.cgColor
    pointerLayer.strokeColor = UIColor.black.cgColor
    pointerLayer.backgroundColor = UIColor.white.cgColor

    layer.addSublayer(pointerLayer)

但我得到的是:

enter image description here

但是,如果我将笔触颜色设置为白色

pointerLayer.strokeColor = UIColor.white.cgColor 

enter image description here 在凹槽中我想在底部有一个rounded edge(就像在第一张照片中一样),当fillColor和strokeColor匹配时(白色),它们不再可见。 我该如何解决? 还有其他方法可以达到这个目的吗?

以下是指针路径的代码:

private func pointerPathForContentSize(contentSize: CGSize) -> UIBezierPath
{
    let rect = CGRect(x: 0, y: 0, width: contentSize.width, height: contentSize.height)

    let width:CGFloat = 20
    let height:CGFloat = 20

    let path = UIBezierPath()


    let startX:CGFloat = 50
    let startY:CGFloat = rect.minY
    path.move(to: CGPoint(x: startX , y: startY))
    path.addLine(to: CGPoint(x: (startX + width*0.5), y: startY + height))


    path.addLine(to: CGPoint(x: (startX + width), y: startY))

    path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
    path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
    path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
    path.addLine(to: CGPoint(x: rect.minX, y: rect.minY))


    path.close()
    return path
}

1 个答案:

答案 0 :(得分:1)

由于您已经通过抚摸路径概述了所需的形状,我认为最简单的解决方案可能是使用描边和填充路径作为掩码。

例如,这是一个矩形的红色视图:

enter image description here

这是同样的红色视图,从顶部切出缺口。这似乎是你之后的事情:

enter image description here

我所做的是用一个特殊的蒙版视图来掩盖红色视图,该视图使用.clear混合模式绘制缺口:

class MaskView : UIView {
    override init(frame: CGRect) {
        super.init(frame:frame)
        self.isOpaque = false
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func draw(_ rect: CGRect) {
        let con = UIGraphicsGetCurrentContext()!
        con.fill(self.bounds)
        con.setBlendMode(.clear)
        con.move(to: CGPoint(x:0, y:-4))
        con.addLine(to: CGPoint(x:100, y:-4))
        con.addLine(to: CGPoint(x:110, y:15))
        con.addLine(to: CGPoint(x:120, y:-4))
        con.addLine(to: CGPoint(x: self.bounds.maxX, y:-4))
        con.addLine(to: CGPoint(x: self.bounds.maxX, y:-20))
        con.addLine(to: CGPoint(x: 0, y:-20))
        con.closePath()
        con.setLineJoin(.round)
        con.setLineWidth(10)
        con.drawPath(using: .fillStroke) // stroke it and fill it
    }
}

那么当我准备在红色视图上切出缺口时,我只想说:

self.redView.mask = MaskView(frame:self.redView.bounds)