Mercurial > public > stock-charts
comparison InteractiveCharts/LineChart/Helpers/LinePath.swift @ 5:f828c7c408d4
Add source code
author | Dennis Concepción Martín <66180929+denniscm190@users.noreply.github.com> |
---|---|
date | Mon, 26 Apr 2021 19:02:46 +0200 |
parents | |
children | 959175ee5ebd |
comparison
equal
deleted
inserted
replaced
4:fd3fb56afc53 | 5:f828c7c408d4 |
---|---|
1 // | |
2 // LinePath.swift | |
3 // InteractiveCharts | |
4 // | |
5 // Created by Dennis Concepción Martín on 26/4/21. | |
6 // | |
7 | |
8 import SwiftUI | |
9 | |
10 struct LinePath: Shape { | |
11 var data: [Double] | |
12 var (width, height): (CGFloat, CGFloat) | |
13 | |
14 func path(in rect: CGRect) -> Path { | |
15 var path = Path() | |
16 | |
17 let normalizedData = normalize(data) | |
18 let widthBetweenDataPoints = Double(width) / Double(normalizedData.count - 1) // Remove first point | |
19 let initialPoint = normalizedData[0] * Double(height) | |
20 var x: Double = 0 | |
21 | |
22 var pathPoints = [CGPoint]() | |
23 | |
24 path.move(to: CGPoint(x: x, y: initialPoint)) | |
25 for y in normalizedData { | |
26 if normalizedData.firstIndex(of: y) != 0 { // Skip first point | |
27 x += widthBetweenDataPoints | |
28 let y = y * Double(height) | |
29 path.addLine(to: CGPoint(x: x, y: y)) | |
30 } | |
31 | |
32 // Append current point to an array. Later will be used for Drag Gesture | |
33 pathPoints.append(path.currentPoint!) | |
34 } | |
35 | |
36 return path | |
37 } | |
38 | |
39 /* | |
40 Get data -> normalize it -> 0 <= output <= 1 | |
41 */ | |
42 func normalize(_ data: [Double]) -> [Double] { | |
43 var normalData = [Double]() | |
44 let min = data.min()! | |
45 let max = data.max()! | |
46 | |
47 for value in data { | |
48 let normal = (value - min) / (max - min) | |
49 normalData.append(normal) | |
50 } | |
51 | |
52 return normalData | |
53 } | |
54 } | |
55 |