2015-04-17 35 views
1

我正在使用CAShapeLayer在視圖中繪製一些形狀。我做了一個功能來管理這個。因此,舉例來說: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") 
     } 
    } 
} 

不幸的是,這似乎並不奏效。有誰知道我正在犯的錯誤?或者,也許我正在以這種錯誤的方式去做?

謝謝!

回答

1

嘗試使用CGPathContainsPoint來檢查圖層路徑中是否包含觸摸的位置。

+0

感謝您的快速響應!你可以給我一個我如何用我的代碼做這個例子嗎? –

+0

'let hitLayer = CGPathContainsPoint(layer.path,nil,location,true)' –

+0

獲取錯誤'條件綁定中的綁定值必須爲可選類型' –