CAShapeLayer 攻丝

CAShapeLayer Tapping

我正在使用 CAShapeLayer 在视图中绘制一些形状。我做了一个功能来管理这个。因此,例如:

viewDidLoad()

drawQuad(UIColor(red: 0.600, green: 0.224, blue: 0.341, alpha: 1.00), firstPoint: CGPointMake(screenWidth * -0.159, screenHeight * 0.249), secondPoint: CGPointMake(screenWidth * 0.65, screenHeight * 0.249), thirdPoint: CGPointMake(screenWidth * 1.01, screenHeight * 0.50), fourthPoint: CGPointMake(screenWidth * 0.399, screenHeight * 0.50))

drawQuad(...)

func drawQuad(fillColor: UIColor, firstPoint: CGPoint, secondPoint: CGPoint, thirdPoint: CGPoint, fourthPoint: CGPoint) {
    let screenWidth = screenSize.width
    let screenHeight = screenSize.height

    let shape = CAShapeLayer()
    containerLayer.addSublayer(shape)
    shape.lineJoin = kCALineJoinMiter
    shape.fillColor = fillColor.CGColor

    let path = UIBezierPath()
    path.moveToPoint(firstPoint)
    path.addLineToPoint(secondPoint)
    path.addLineToPoint(thirdPoint)
    path.addLineToPoint(fourthPoint)

    path.closePath()
    shape.path = path.CGPath
}

我无法尝试为每个形状添加点击识别。我试图做的是创建一个容器 CAShapeLayer,将每个形状作为一个子层。如果您查看上面的函数,您会在第 6 行看到它。然后,在 viewDidLoad() 中,我将最终的容器层添加到视图中。

这样做的目的是能够像这样hitTest

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    let touch = touches.first as! UITouch
    let location = touch.locationInView(self.view)

    for layer in containerLayer.sublayers {
        if let hitLayer = layer.hitTest(location) {
            println("Tapped")
        }
    }
}

不幸的是,这似乎不起作用。有谁知道我犯的错误?或者我可能用错了方法?

谢谢!

尝试使用CGPathContainsPoint检查触摸的位置是否包含在图层路径中。