Swift: как использовать Hit Test & amp; Безье, чтобы коснуться частей тела? [Дубликат]

Swift 3

["I Love","Swift"].joined(separator:" ") // previously joinWithSeparator(" ")
9
задан blancos 27 March 2014 в 18:09
поделиться

4 ответа

Функция CGPathContainsPoint() может быть полезна в вашем случае.

Также будьте осторожны, если вы получите точку жестов из супервизора, координата может оказаться неправильной с вашим тестом. У вас есть метод конвертации точки из или в систему координат конкретного вида:

- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view
- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view
14
ответ дан foOg 22 August 2018 в 07:00
поделиться

Обнаружение касания внутри пути безье в быстром: -

Это просто в последнем быстром, выполните следующие действия, и вы получите событие касания UIBezierPath.

Шаг 1: - Инициализировать Нажмите Событие на просмотр, где добавлен ваш UIBeizerPath.

///Catch layer by tap detection let tapRecognizer:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(YourClass.tapDetected(_:))) viewSlices.addGestureRecognizer(tapRecognizer)

Шаг 2: - Сделайте метод «tapDetected»

  //MARK:- Hit TAP
public func tapDetected(tapRecognizer:UITapGestureRecognizer){
    let tapLocation:CGPoint = tapRecognizer.locationInView(viewSlices)
    self.hitTest(CGPointMake(tapLocation.x, tapLocation.y))


}

Шаг 3: - Сделайте окончательный метод «hitTest»

  public func hitTest(tapLocation:CGPoint){
        let path:UIBezierPath = yourPath
        if path.containsPoint(tapLocation){
            //tap detected do what ever you want ..;)
        }else{
             //ooops you taped on other position in view
        }
    }

Обновление: Swift 4

Шаг 1: - Инициализировать событие Tap на экране, где добавлен ваш UIBeizerPath.

///Catch layer by tap detection
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(YourClass.tapDetected(tapRecognizer:)))
viewSlices.addGestureRecognizer(tapRecognizer)

Шаг 2: - Сделайте метод «tapDetected»

public func tapDetected(tapRecognizer:UITapGestureRecognizer){
    let tapLocation:CGPoint = tapRecognizer.location(in: viewSlices)
    self.hitTest(tapLocation: CGPoint(x: tapLocation.x, y: tapLocation.y))
}

Шаг 3: - Сделайте окончательный метод «hitTest»

private func hitTest(tapLocation:CGPoint){
    let path:UIBezierPath = yourPath

    if path.contains(tapLocation){
        //tap detected do what ever you want ..;)
    }else{
        //ooops you taped on other position in view
    }
}
4
ответ дан Diogo Souza 22 August 2018 в 07:00
поделиться

Решение в Swift 3.1 (портирование рекомендованного Apple решения из здесь )

func containsPoint(_ point: CGPoint, path: UIBezierPath, inFillArea: Bool) -> Bool {

        UIGraphicsBeginImageContext(self.size)

        let context: CGContext? = UIGraphicsGetCurrentContext()
        let pathToTest = path.cgPath
        var isHit = false

        var mode: CGPathDrawingMode = CGPathDrawingMode.stroke

        if inFillArea {

            // check if UIBezierPath uses EO fill
            if path.usesEvenOddFillRule {
                mode = CGPathDrawingMode.eoFill
            } else {
                mode = CGPathDrawingMode.fill
            }
        } // else mode == stroke

        context?.saveGState()
        context?.addPath(pathToTest)

        isHit = (context?.pathContains(point, mode: mode))!
        context?.restoreGState()

        return isHit
        }
1
ответ дан JaredH 22 August 2018 в 07:00
поделиться
Другие вопросы по тегам:

Похожие вопросы: