Skip to content

Instantly share code, notes, and snippets.

@charlesetc
Created December 11, 2022 02:59

Revisions

  1. charlesetc renamed this gist Dec 11, 2022. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. charlesetc created this gist Dec 11, 2022.
    80 changes: 80 additions & 0 deletions SwiftUI spatial canvas
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,80 @@
    //
    // ContentView.swift
    // Apricot
    //
    // Created by Charles Chamberlain on 12/10/22.
    //

    import SwiftUI

    extension Color {
    static func random() -> Color {
    return Color(red: Double.random(in: 0...1), green: Double.random(in: 0...1), blue: Double.random(in: 0...1))
    }
    }

    struct SpatialCanvas: View {
    @State private var circles = [CircleData]()

    var body: some View {
    ZStack {
    ForEach(circles.indices, id: \.self) { index in
    Circle()
    .fill(circles[index].color)
    .frame(width: circles[index].diameter, height: circles[index].diameter)
    .offset(circles[index].offset)
    .gesture(
    DragGesture()
    .onChanged { value in
    circles[index].offset = value.translation
    }
    .onEnded { _ in
    circles[index].offset = .zero
    }
    )
    }
    }
    .onAppear {
    circles = [
    CircleData(color: .red, diameter: 100, offset: CGSize(width: 10, height: 20)),
    CircleData(color: .green, diameter: 30 , offset: CGSize(width: 20, height: 30)),
    CircleData(color: .blue, diameter: 25, offset: CGSize(width: 50 , height: 50)),
    ]
    }
    .toolbar {
    ToolbarItem(placement: .automatic) {
    Button(action: addCircle) {
    Image(systemName: "plus")
    }
    }
    }
    }

    private func addCircle() {
    let randomColor = Color.random()
    let randomDiameter = CGFloat.random(in: 25...100)
    let randomXOffset = CGFloat.random(in: -150...150)
    let randomYOffset = CGFloat.random(in: -150...150)
    circles.append(CircleData(color: randomColor, diameter: randomDiameter, offset: CGSize(width: randomXOffset, height: randomYOffset)))
    }

    private struct CircleData {
    var color: Color
    var diameter: CGFloat
    var offset: CGSize
    }
    }

    struct ContentView: View {
    var body: some View {
    return SpatialCanvas().padding().frame(minWidth: 200, minHeight: 400)
    }
    }

    struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
    Group {
    ContentView()
    }
    }
    }