오늘은 SwiftUI Canvas UnitPointPosition비슷한개념) 이용해서 그림을 그려보는것을 해보자!
struct Particle: Hashable {
let x: Double
let y: Double
let createionDate = Date.now.timeIntervalSinceReferenceDate
let hue: Double
}
class ParticleSysytem {
let image = Image("spark")
var particles = Set<Particle>()
var center = UnitPoint.center
var hue = 0.0
func update(date: TimeInterval) {
let deathDate = date - 1
for particle in particles {
if particle.createionDate < deathDate {
particles.remove(particle)
}
}
let newParticle = Particle(x:center.x, y: center.y, hue: hue)
particles.insert(newParticle)
hue += 0.01
if hue > 1 { hue -= 1 }
}
}
우선 파티클이라는 최소단위 struct 생성하고 파니클은 좌표값x,y그리고 객체생성시 Date값을 가진다 그리고 hut라는 colorpoint 변수를 가진다 ParticleSystem클래스는 파티클이미지와 그 이미지를 Set Collection 담아서 UnitPoint가운데를가지는 포지션을 가지고 그리고 Update함수를 사용해서 particles Set콜렉션에 파티클을 추가한다
struct ContentView: View {
@State private var particleSystem = ParticleSysytem()
@State private var motionHandler = MotionManageer()
let options: [(flipX: Bool, flipY: Bool)] = [
(false, false),
(true, false),
(false, true),
(true, true)
]
var body: some View {
TimelineView(.animation) { timeline in
Canvas { context, size in
let timelineData = timeline.date.timeIntervalSinceReferenceDate
particleSystem.update(date: timelineData)
context.blendMode = .plusLighter
particleSystem.center = UnitPoint(x: 0.5 + motionHandler.roll, y: 0.5 + motionHandler.pitch)
for particle in particleSystem.particles {
var contextCopy = context
contextCopy.addFilter(.colorMultiply(Color(hue: particle.hue, saturation: 1, brightness: 1 )))
contextCopy.opacity = 1 - (timelineData - particle.createionDate)
for option in options {
var xPos = particle.x * size.width
var yPos = particle.y * size.height
if option.flipX {
xPos = size.width - xPos
}
if option.flipY {
yPos = size.height - yPos
}
contextCopy.draw(particleSystem.image, at: CGPoint(x:xPos, y: yPos))
}
}
}
}
.gesture(DragGesture(minimumDistance: 0).onChanged{ drag in
particleSystem.center.x = drag.location.x / UIScreen.main.bounds.width
particleSystem.center.y = drag.location.y / UIScreen.main.bounds.height
}
)
.ignoresSafeArea()
.background(.black)
}
}
ContentView다음 코드를 사용하면 rainbow색이 변하고 4개의 대칭구조를 가지는 particle생성해서 드래그 제스처를 이용하여 움직이는 네온사인생성이 가능하다![](https://velog.velcdn.com/images/dnrur124/post/405fd0ba-d8c9-4fe9-baef-507eaccdbaf4/image.png)