Skip to content

Instantly share code, notes, and snippets.

@charlesetc
Created December 11, 2022 02:59
Show Gist options
  • Save charlesetc/d16de266930a40f70fd6d102616a2b9d to your computer and use it in GitHub Desktop.
Save charlesetc/d16de266930a40f70fd6d102616a2b9d to your computer and use it in GitHub Desktop.
//
// 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()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment