繪製不規則圖形並響應點選事件

d_d發表於2018-10-27

需求

繪製一個不規則圖形並能響應點選事件

思路

1.使用CAShapeLayer繪製圖形

2.在點選螢幕時判斷觸控點是否落在CAShapeLayerpath內部

實現

1.畫出不規則圖形的path

private func createPolygonPath() -> CGPath {
        let path = UIBezierPath()
        path.move(to: CGPoint(x: 100, y: 200))
        path.addLine(to: CGPoint(x: 100, y: 400))
        path.addLine(to: CGPoint(x: 300, y: 400))
        path.addLine(to: CGPoint(x: 100, y: 200))
        return path.cgPath
    }
複製程式碼

2.畫出需要的layer:

private func createPolygonLayer() -> CALayer {
        let polygonLayer = CAShapeLayer()
        polygonLayer.fillColor = UIColor.purple.cgColor
        polygonLayer.lineWidth = 1.0
        polygonLayer.strokeColor = UIColor.red.cgColor
        polygonPath = createPolygonPath()
        polygonLayer.path = polygonPath!
        return polygonLayer
    }
複製程式碼

3.點選時的邏輯處理:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let touchPoint = touch.location(in: view)
            if let polygonPath = polygonPath, polygonPath.contains(touchPoint) {
                print("polygonLayer was touched")
            }
        }
    }
複製程式碼

相關文章