代码之家  ›  专栏  ›  技术社区  ›  Joel

快速检测绘图中的触摸位置:

  •  0
  • Joel  · 技术社区  · 7 年前

    提前致歉这是我第一次发布问题,我是一个初学者,但已刮论坛和文件;

    要创建的图形类型,单击以查看

    enter image description here

    如果我要创建一个类似于所附照片的图形,有没有一种方法可以根据所点击的段来执行函数。

    是否有方法将发件人标记添加到在绘图中创建的形状, 例如

    // In custom drawing class
    override func draw(_ rect: CGRect) {
        let shape1 = UIBezierPath() // code for segment 1
        let shape2 = UIBezierPath() // code for segment 2
        let shape3 = UIBezierPath() // code for segment 3
        // etc, etc
        shape1.tag = 1
        shape2.tag = 2
        shape3.tag = 3
        // etc
    }
    
    // In ViewController.swift
    @IBAction func shapeButtonFunction(_ shape: Any) {
        if shape.tag == 0 {
            // do this
        }
        else if shpae.tag == 1 {
            // do this
        }
    }
    

    本质上,我可以创建闭合的形状,并通过使用某种可以识别的标记来确定它们是什么时候被点击的吗?

    非常感谢您的帮助!

    1 回复  |  直到 7 年前
        1
  •  0
  •   Satachito    7 年前

    uibezierpath具有“contains”方法。

    func contains(_ point: CGPoint) -> Bool

    所以,在touchesStarted或toucheSend中使用此方法保存形状并测试命中率。

    class   SomeV: UIView {
        var shape1 = UIBezierPath()
        var shape2 = UIBezierPath()
        var shape3 = UIBezierPath()
        override func draw(_ rect: CGRect) {
            shape1 = UIBezierPath() // code for segment 1
            shape2 = UIBezierPath() // code for segment 2
            shape3 = UIBezierPath() // code for segment 3
            // etc
        }
        override func
        touchesEnded( _ touches: Set<UITouch>, with event: UIEvent? ) {
            if let w = touches.first?.location( in: self ) {
                if shape1.contains( w ) { print( "Touches in shape1" ) }
                if shape2.contains( w ) { print( "Touches in shape1" ) }
                if shape3.contains( w ) { print( "Touches in shape1" ) }
            }
        }
    }