diff Sources/StockCharts/LineChart/Helpers/LinePath.swift @ 21:5135ff3343ae

Rename project to StockCharts
author Dennis Concepción Martín <66180929+denniscm190@users.noreply.github.com>
date Fri, 30 Apr 2021 17:40:33 +0200
parents Sources/InteractiveCharts/LineChart/Helpers/LinePath.swift@136de51a74f2
children 127af64e264e
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Sources/StockCharts/LineChart/Helpers/LinePath.swift	Fri Apr 30 17:40:33 2021 +0200
@@ -0,0 +1,54 @@
+//
+//  LinePath.swift
+//  StockCharts
+//
+//  Created by Dennis Concepción Martín on 30/4/21.
+//
+
+import SwiftUI
+
+public struct LinePath: Shape {
+    var data: [Double]
+    var (width, height): (CGFloat, CGFloat)
+    @Binding var pathPoints: [CGPoint]
+    
+    public func path(in rect: CGRect) -> Path {
+        var path = Path()
+        
+        let normalizedData = normalize(data)
+        let widthBetweenDataPoints = Double(width) / Double(normalizedData.count - 1)  // Remove first point
+        let initialPoint = normalizedData[0] * Double(height)
+        var x: Double = 0
+        
+        path.move(to: CGPoint(x: x, y: initialPoint))
+        for y in normalizedData {
+            if normalizedData.firstIndex(of: y) != 0 {  // Skip first point
+                x += widthBetweenDataPoints
+                let y = y * Double(height)
+                path.addLine(to: CGPoint(x: x, y: y))
+            }
+
+            // Append current point to an array. Later will be used for Drag Gesture
+            pathPoints.append(path.currentPoint!)
+        }
+        
+        return path
+    }
+    
+    /*
+     Get data -> normalize it -> 0 <= output <= 1
+     */
+    public func normalize(_ data: [Double]) -> [Double] {
+        var normalData = [Double]()
+        let min = data.min()!
+        let max = data.max()!
+
+        for value in data {
+            let normal = (value - min) / (max - min)
+            normalData.append(normal)
+        }
+        
+        return normalData
+    }
+}
+