So i am just playing around and making a Christmas tree....I have a Triangle shape and I wanted to put random colored dots inside of the the triangle to simulate lights on the tree. I have done that but since they are randomly generated, it is hard to get them to not display outside of the shape (the Triangle). I created the view below in hopes to reuse the view to place different size trees into ContentView. The thought was to have this shape have the random dots be self contained inside of the shape, no matter the size of the Triangle, or even the size of any shape... any ideas? Here is what I have. Again, just playing around on Christmas vacation :)
import SwiftUI
struct Triangle: Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: rect.midX, y: rect.minY))
path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.midX, y: rect.minY))
return path
}
}
struct BubbleViewSmall: View {
@State private var scale : CGFloat = 1.0
var body: some View {
ZStack {
ForEach (1...100, id:\.self) { _ in
//red
Circle ()
.foregroundColor(.red)
.blendMode(.colorDodge) // The bottom circle is lightened by an amount determined by the top layer
.animation (Animation.spring (dampingFraction: 0.5).repeatForever()
.speed (.random(in: 0.4...1.5))
.delay(.random (in: 0...1)), value: scale)
.scaleEffect(self.scale * .random(in: 0.1...2))
.frame(width: .random(in: 1...20),
height: CGFloat.random (in: 10...25),
alignment: .center)
.position(CGPoint(x: .random(in: 150...250),
y: .random (in: 250...550)))
//white
Circle ()
.foregroundColor(.white)
.blendMode(.colorDodge) // The bottom circle is lightened by an amount determined by the top layer
.animation (Animation.spring (dampingFraction: 0.5).repeatForever()
.speed (.random(in: 0.4...1.5))
.delay(.random (in: 0...1)), value: scale)
.scaleEffect(self.scale * .random(in: 0.1...1.5))
.frame(width: .random(in: 1...20),
height: CGFloat.random (in: 10...25),
alignment: .center)
.position(CGPoint(x: .random(in: 150...250),
y: .random (in: 250...550)))
//green
Circle()
.foregroundColor(.green)
.blendMode(.colorDodge) // The bottom circle is lightened by an amount determined by the top layer
.animation (Animation.spring (dampingFraction: 0.5).repeatForever()
.speed (.random(in: 0.4...1.5))
.delay(.random (in: 0...1)), value: scale)
.scaleEffect(self.scale * .random(in: 0.1...1.5))
.frame(width: .random(in: 1...20),
height: CGFloat.random (in: 10...25),
alignment: .center)
.position(CGPoint(x: .random(in: 150...250),
y: .random (in: 250...550)))
}
}
.onAppear { self.scale = 0.5 } // default circle scale
.drawingGroup(opaque: false, colorMode: .linear)
.background(
Triangle()
.stroke(.white, lineWidth: 30)
.fill(.darkGreen)
.frame(width: 350, height: 400))
}//view
}
#Preview {
BubbleViewSmall()
}