使用 Pan Gesture 将 UIView 拖到 UIBezierPath 上

Posted

技术标签:

【中文标题】使用 Pan Gesture 将 UIView 拖到 UIBezierPath 上【英文标题】:Drag UIView over UIBezierPath with Pan Gesture 【发布时间】:2020-07-27 05:50:13 【问题描述】:

我使用 UIBezierPath 创建了一个图表。它基本上是一段时间内的货币换算图。因此用户可以拖动手指来查看路径上的值。当用户拖动手指时,如何获取 BezierPath 的 Y 值来调整我的 UIView 框架。

我使用apply(info: UnsafeMutableRawPointer?, function: CGPathApplierFunction) 在 CGPath 上获得积分,但我认为它们不足以获得良好的结果

我需要什么



我使用 UIBezierPath 实现的目标



任何指针都会有帮助...谢谢

这是我目前尝试过的


class GraphView: UIView 
    @IBInspectable var startColor: UIColor = .red
     @IBInspectable var endColor: UIColor = .green

    var data: [CGFloat] = [2, 3 , 2.9 ,2.8,6,5,7,1,3,2,8,8.2,9,5,6,4, 10,5, 4,2,5,7,12 ,10,11,10.5,11, 13,10] 
        didSet 
            setNeedsDisplay()
        
    

    func coordYFor(index: Int) -> CGFloat 
        return bounds.height - bounds.height * data[index] / (data.max() ?? 0)
    

    override func draw(_ rect: CGRect) 

      

        
         
         let path = quadCurvedPath()
        
        
        
        
        var bezierPoints = NSMutableArray()

        path.cgPath.apply(info: &bezierPoints, function:  info, element in

            guard let resultingPoints = info?.assumingMemoryBound(to: NSMutableArray.self) else 
                return
            

            let points = element.pointee.points
            let type = element.pointee.type

            switch type 
            case .moveToPoint:
                resultingPoints.pointee.add([NSNumber(value: Float(points[0].x)), NSNumber(value: Float(points[0].y))])

            case .addLineToPoint:
                resultingPoints.pointee.add([NSNumber(value: Float(points[0].x)), NSNumber(value: Float(points[0].y))])

            case .addQuadCurveToPoint:
                resultingPoints.pointee.add([NSNumber(value: Float(points[0].x)), NSNumber(value: Float(points[0].y))])
                resultingPoints.pointee.add([NSNumber(value: Float(points[1].x)), NSNumber(value: Float(points[1].y))])

            case .addCurveToPoint:
                resultingPoints.pointee.add([NSNumber(value: Float(points[0].x)), NSNumber(value: Float(points[0].y))])
                resultingPoints.pointee.add([NSNumber(value: Float(points[1].x)), NSNumber(value: Float(points[1].y))])
                resultingPoints.pointee.add([NSNumber(value: Float(points[2].x)), NSNumber(value: Float(points[2].y))])

            case .closeSubpath:
                break
            @unknown default:
                break
            
        )
        
        
        print(bezierPoints)
        
    
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = #colorLiteral(red: 0.3669792414, green: 0.2084159851, blue: 0.6959738135, alpha: 1)
        shapeLayer.lineWidth = 3
    
        shapeLayer.lineDashPattern = [4,5]
        shapeLayer.path = path.cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor
        layer.addSublayer(shapeLayer)
        
        
        
        guard let clippingPath = path.copy() as? UIBezierPath else 
          return
        
          let height = rect.height
          
        clippingPath.addLine(to: CGPoint(
          x: bounds.width ,
          y: height))
        clippingPath.addLine(to: CGPoint(x: 0 , y: height))
        clippingPath.close()
            
        clippingPath.addClip()
            


        let shape = CAShapeLayer()
        shape.frame = bounds
        shape.path = clippingPath.cgPath
        shape.fillColor = UIColor.blue.cgColor

        let gradient = CAGradientLayer()
        gradient.frame = bounds
        gradient.colors = [#colorLiteral(red: 0.9705377221, green: 0.9600282311, blue: 0.9863556027, alpha: 1).cgColor,
                           UIColor.white.cgColor]
//        gradient.startPoint = CGPoint(x: 1, y: 0.5)
//        gradient.endPoint = CGPoint(x: 1, y: 0.5)
        
        gradient.locations = [0.5,1.0]
        gradient.mask = shape

        layer.addSublayer(gradient)
        
        
        
        // 5 - Check clipping path - Temporary code
      //  UIColor.green.setFill()
//        let rectPath = UIBezierPath(rect: rect)
//        rectPath.fill()
        //layer.lineDashPattern = [2,3]
        
//        UIColor.blue.setStroke()
//        path.lineWidth = 1
//        path.stroke()
    

    func quadCurvedPath() -> UIBezierPath 
        let path = UIBezierPath()
        let step = bounds.width / CGFloat(data.count - 1)

        var p1 = CGPoint(x: 0, y: coordYFor(index: 0))
        path.move(to: p1)

        drawPoint(point: p1, color: UIColor.red, radius: 3)

        if (data.count == 2) 
            path.addLine(to: CGPoint(x: step, y: coordYFor(index: 1)))
            return path
        

        var oldControlP: CGPoint?

        for i in 1..<data.count 
            let p2 = CGPoint(x: step * CGFloat(i), y: coordYFor(index: i))
            drawPoint(point: p2, color: UIColor.red, radius: 3)
            var p3: CGPoint?
            if i < data.count - 1 
                p3 = CGPoint(x: step * CGFloat(i + 1), y: coordYFor(index: i + 1))
            

            let newControlP = controlPointForPoints(p1: p1, p2: p2, next: p3)

            path.addCurve(to: p2, controlPoint1: oldControlP ?? p1, controlPoint2: newControlP ?? p2)

            p1 = p2
            oldControlP = antipodalFor(point: newControlP, center: p2)
        
        return path;
    

    /// located on the opposite side from the center point
    func antipodalFor(point: CGPoint?, center: CGPoint?) -> CGPoint? 
        guard let p1 = point, let center = center else 
            return nil
        
        let newX = 2 * center.x - p1.x
        let diffY = abs(p1.y - center.y)
        let newY = center.y + diffY * (p1.y < center.y ? 1 : -1)

        return CGPoint(x: newX, y: newY)
    

    /// halfway of two points
    func midPointForPoints(p1: CGPoint, p2: CGPoint) -> CGPoint 
        return CGPoint(x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2);
    

    /// Find controlPoint2 for addCurve
    /// - Parameters:
    ///   - p1: first point of curve
    ///   - p2: second point of curve whose control point we are looking for
    ///   - next: predicted next point which will use antipodal control point for finded
    func controlPointForPoints(p1: CGPoint, p2: CGPoint, next p3: CGPoint?) -> CGPoint? 
        guard let p3 = p3 else 
            return nil
        

        let leftMidPoint  = midPointForPoints(p1: p1, p2: p2)
        let rightMidPoint = midPointForPoints(p1: p2, p2: p3)

        var controlPoint = midPointForPoints(p1: leftMidPoint, p2: antipodalFor(point: rightMidPoint, center: p2)!)

        if p1.y.between(a: p2.y, b: controlPoint.y) 
            controlPoint.y = p1.y
         else if p2.y.between(a: p1.y, b: controlPoint.y) 
            controlPoint.y = p2.y
        


        let imaginContol = antipodalFor(point: controlPoint, center: p2)!
        if p2.y.between(a: p3.y, b: imaginContol.y) 
            controlPoint.y = p2.y
        
        if p3.y.between(a: p2.y, b: imaginContol.y) 
            let diffY = abs(p2.y - p3.y)
            controlPoint.y = p2.y + diffY * (p3.y < p2.y ? 1 : -1)
        

        // make lines easier
        controlPoint.x += (p2.x - p1.x) * 0.4

        return controlPoint
    

    func drawPoint(point: CGPoint, color: UIColor, radius: CGFloat) 
        let ovalPath = UIBezierPath(ovalIn: CGRect(x: point.x - radius, y: point.y - radius, width: radius * 2, height: radius * 2))
        color.setFill()
        ovalPath.fill()
    



extension CGFloat 
    func between(a: CGFloat, b: CGFloat) -> Bool 
        return self >= Swift.min(a, b) && self <= Swift.max(a, b)
    

【问题讨论】:

【参考方案1】:

我是如何解决它的.. 我写信是为了帮助其他试图实现相同目标的人....结果

【讨论】:

以上是关于使用 Pan Gesture 将 UIView 拖到 UIBezierPath 上的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Pan Gesture 增加/减少字体大小?

UIPan Gesture 和 UI Swipe Gesture 在同一个视图中

Spritekit中的Pan Gesture Recognizer移动对象

为所有 UIScrollView 的子类为 Pan Gesture 提供标签

在 xib 文件中使用拖放时将调用 UIView 的哪个 init 方法

将手指拖离它时取消选择 UIView“按钮”