Ich benutze CAShapeLayer, um eine Linie auf dem Bildschirm zu zeichnen. In der Methode touchesEnded Ich möchte überprüfen, "Passiert die Linie durch den Punkt?". In meinem Code, wenn ich auf einen beliebigen Teil des Bildschirms drücken, die Methode enthält gibt immer wahr. Vielleicht habe ich ein Problem in line.frame = (view? .bounds)!. Wie kann ich es reparieren? Sorry für mein schlechtes Englisch.CAShapeLayer. Geht die Linie durch den Punkt?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let firstPosition = touch?.location(in: self)
if atPoint(firstPosition!) == lvl1 {
let firstPositionX = firstPosition?.x
let firstPositionY = frame.size.height - (firstPosition?.y)!
view?.layer.addSublayer(line)
line.lineWidth = 8
let color = #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1).cgColor
line.strokeColor = color
line.fillColor = nil
line.frame = (view?.bounds)!
path.move(to: CGPoint(x: firstPositionX!, y: firstPositionY))
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let firstPosition = touch?.location(in: self)
if atPoint(firstPosition!) == lvl1 {
let firstPositionX = firstPosition?.x
let firstPositionY = frame.size.height - (firstPosition?.y)!
path.addLine(to: CGPoint(x: firstPositionX!, y: firstPositionY))
line.path = path.cgPath
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if line.contains(screenCenterPoint) {
print("ok")
}
}
Ich würde vorschlagen, den Abstand zwischen einem [Liniensegment und einem Punkt] (http://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line) zu berechnen und sehen, ob es unter einen Wert fällt. – Rob