aboutsummaryrefslogtreecommitdiff
path: root/Map/Presentation/Base Components/MapRender/MapGroup.swift
blob: 9df333815c213871e175d0333ba2c68545ef4760 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import ConcaveHull
import SwiftUI

struct MapGroup: View {

  let mapSize: CGSize
  let vertexSize: CGSize
  let group: [Vertex]
  let color: Color

  let cornerSize = CGSize(width: 2.0, height: 2.0)
  var strokeSize: CGFloat { 1.75 * vertexSize.width }

  var hull: [CGPoint] {
    let groupList = group.map({ vertex in
      return [Double(vertex.position.x), Double(vertex.position.y)]
    })
    let hull = Hull()
    let hullPoints = hull.hull(groupList, nil)
    return hullPoints.compactMap({ object in
      if let point = object as? [Double] {
        return CGPoint(x: point[0], y: point[1])
      }
      return nil
    })
  }

  var body: some View {
    Path { path in
      var initialMove: CGPoint?

      for point in hull {
        let offsetPoint = CGPoint(x: w(point.x), y: h(point.y))

        if initialMove == nil {
          path.move(to: offsetPoint)
          initialMove = offsetPoint
        } else {
          path.addLine(to: offsetPoint)
        }
      }

      if let initialMove = initialMove {
        path.addLine(to: initialMove)
      }

    }
    .applying(
      CGAffineTransform(translationX: vertexSize.width / 2.0, y: vertexSize.height / 2.0)
    )
    .fill(color)
    .stroke(
      color,
      style: StrokeStyle(
        lineWidth: strokeSize,
        lineCap: .round,
        lineJoin: .round,
        miterLimit: 0,
        dash: [],
        dashPhase: 0
      )
    )
  }

  func h(_ dimension: CGFloat) -> CGFloat {
    max(0.0, min(mapSize.height, dimension * mapSize.height / 100.0))
  }

  func w(_ dimension: CGFloat) -> CGFloat {
    max(0.0, min(mapSize.width, dimension * mapSize.width / 100.0))
  }
}

#Preview {
  MapGroup(
    mapSize: CGSize(width: 400.0, height: 400.0), vertexSize: CGSize(width: 25.0, height: 25.0),
    group: [
      Vertex(id: 0, label: "A Circle", position: CGPoint(x: 50.0, y: 50.0)),
      Vertex(id: 1, label: "A Square", position: CGPoint(x: 10.0, y: 20.0), shape: .square),
      Vertex(id: 2, label: "A triangle", position: CGPoint(x: 25, y: 32.0), shape: .triangle),
      Vertex(id: 3, label: "An X", position: CGPoint(x: 70.0, y: 70.0), shape: .x),
    ], color: .red)
}