首页 文章

Swift:如何从Override func of touch中提取CGPoint数字?

提问于
浏览
0

我使用下面显示的代码让用户触摸和绘图 . 在触摸期间,用户总是离开CGPoint或他/她的第一次和最后一次触摸的坐标 .

var lastPoint: CGPoint!
var firstPoint: CGPoint!
var swiped: Bool!
var allowTouches = true



override func touchesBegan(touches: Set<UITouch>,
                        withEvent event: UIEvent?) {
    guard allowTouches else {
        return
    }


    swiped    = false
    if let touch = touches.first {
    lastPoint = touch.locationInView(self.imageView)
      firstPoint = lastPoint

    }

}


 override func touchesMoved(touches: Set<UITouch>,
                            withEvent event: UIEvent?) {

    guard allowTouches else {
        return
    }


    swiped = true;

    if let touch = touches.first {

        let currentPoint = touch.locationInView(imageView)
        UIGraphicsBeginImageContext(self.imageView.frame.size)
        self.imageView.image?.drawInRect(CGRectMake(0, 0, self.imageView.frame.size.width, self.imageView.frame.size.height))

        CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y)
        CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y)
        CGContextSetLineCap(UIGraphicsGetCurrentContext(),CGLineCap.Round)
        CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0)

        CGContextStrokePath(UIGraphicsGetCurrentContext())
        self.imageView.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()


        lastPoint = currentPoint

          }

      }

正如您在代码中看到的,当用户触摸屏幕时,firstPoint保存坐标,然后在滑动然后移除触摸之后,lastPoint保存坐标 .

我的问题:如何从override fi返回这两个坐标(firstPoint和lastPoint)?这样我就可以将这两个值用于覆盖func之外的其他计算 .

1 回答

  • 0

    使用

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?)
    

    用户选择手指时计算最后一点触摸的方法 . 由于您已将它们声明为var和全局变量,因此您可以在类的任何函数(方法)中使用它们 . 只需计算lastPoint和firstPoint之间的差异,您就可以得到距离 .

相关问题