【问题标题】:Swift: How to pull out CGPoint number from Override func of touch?斯威夫特:如何从触摸覆盖功能中提取 CGPoint 数字?
【发布时间】:2016-10-01 19:41:30
【问题描述】:

我正在使用下面显示的代码让用户触摸和绘图。在触摸它的过程中,用户总是离开 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 保存坐标。

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

【问题讨论】:

  • “把那两个坐标拉出来”是什么意思?
  • 你的问题一点都不清楚。请尝试更好地解释您正在尝试做什么。
  • 这两个变量是实例变量。您可以在任何实例方法中使用它们。除了你已经在做的事情之外,你不需要做任何事情。也许您应该用您正在尝试做的事情来更新您的问题。
  • 假设,我正在考虑测量这两个坐标之间的距离并将距离显示给用户。对于这些,我需要覆盖函数之外的这两个坐标,对吗?或者我可以在 override func 里面做吗?

标签: ios coordinates cgpoint


【解决方案1】:

使用

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

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

【讨论】:

    猜你喜欢
    • 2016-10-21
    • 1970-01-01
    • 2017-07-07
    • 2017-07-22
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多