Created
February 9, 2023 19:42
-
-
Save treboc/d937dfa69c770082025e42a3cffb6d69 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
let size: CGSize = CGSize(width: 200, height: 200) | |
@State private var positions = [CGRect]() | |
@State private var counter = 0 | |
var body: some View { | |
ZStack { | |
ForEach(positions, id: \.self) { position in | |
Image(systemName: "gift") | |
.position(x: position.midX, y: position.midY) | |
.rotationEffect(Angle(degrees: makeRotationAngle())) | |
.scaleEffect(.random(in: 0.7...1.5)) | |
.foregroundColor(.secondary) | |
} | |
} | |
.clipped() | |
.frame(width: 200, height: 200) | |
.background(.white) | |
.cornerRadius(16) | |
.frame(maxWidth: .infinity, maxHeight: .infinity) | |
.background(.black) | |
.ignoresSafeArea() | |
.onAppear { | |
makePositions() | |
} | |
} | |
func makePositions() { | |
while positions.count < 50 { | |
let randomPosition = makePosition(in: size) | |
print(randomPosition) | |
if !containsPosition(randomPosition) { | |
positions.append(randomPosition) | |
print("Append!") | |
counter += 1 | |
print(counter) | |
} | |
} | |
} | |
func containsPosition(_ position: CGRect) -> Bool { | |
positions.contains { $0.intersects(position) } | |
} | |
func makePosition(in size: CGSize) -> CGRect { | |
let xPos = Int.random(in: 0..<Int(size.width)) | |
let yPos = Int.random(in: 0..<Int(size.height)) | |
return CGRect(x: CGFloat(xPos), y: CGFloat(yPos), width: 10, height: 10) | |
} | |
func makeRotationAngle() -> Double { | |
Double.random(in: -15...15) | |
} | |
} | |
extension CGRect: Hashable { | |
public func hash(into hasher: inout Hasher) { | |
hasher.combine(self.midX) | |
hasher.combine(self.midY) | |
} | |
} | |
struct SizePreferenceKey: PreferenceKey { | |
static var defaultValue: CGSize = .zero | |
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {} | |
} | |
extension View { | |
func readSize(onChange: @escaping (CGSize) -> Void) -> some View { | |
background( | |
GeometryReader { geo in | |
Color.clear | |
.preference(key: SizePreferenceKey.self, value: geo.size) | |
} | |
) | |
.onPreferenceChange(SizePreferenceKey.self, perform: onChange) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment