[swift] CoreAnimation 레이어 애니메이션 루프

CoreAnimation은 iOS 앱에서 애니메이션을 만들고 제어하는 강력한 도구입니다. 때때로, 특히 반복되는 애니메이션을 만들고자 할 때, 레이어 애니메이션을 루프(loop)시켜야 할 수 있습니다.

레이어 애니메이션 생성

let animation = CABasicAnimation(keyPath: "position")
animation.fromValue = NSValue(cgPoint: CGPoint(x: 100, y: 100))
animation.toValue = NSValue(cgPoint: CGPoint(x: 300, y: 300))
animation.duration = 2.0
layer.add(animation, forKey: "position")

위의 코드는 사각형이 (100, 100) 부터 (300, 300)까지 2초 동안 움직이는 애니메이션을 만드는 예제입니다.

애니메이션 루핑(looping)

레이어 애니메이션을 루핑시키기 위해서는 animation 객체의 repeatCount 속성을 설정합니다.

animation.repeatCount = .greatestFiniteMagnitude

repeatCount 속성을 greatestFiniteMagnitude로 설정하면 애니메이션이 무한히 반복됩니다.

애니메이션의 시작과 종료

또한, 애니메이션의 시작 시간과 종료 시간을 설정하여 루프를 원하는 구간동안만 하도록 제어할 수도 있습니다. 이를 위해서 beginTimeendTime 속성을 사용합니다.

animation.beginTime = CACurrentMediaTime() + 1 // 1초 후에 애니메이션이 시작됨
animation.duration = 2.0 // 애니메이션은 2초간 반복됨
animation.repeatCount = 5 // 애니메이션은 총 5번 반복됨
animation.autoreverses = true // 애니메이션이 끝나면 역방향으로 애니메이션이 실행됨

위의 설정을 사용하면, 1초 후에 시작하여 2초 간 총 5번 반복되는 애니메이션을 만들 수 있습니다.

CoreAnimation을 사용하여 레이어 애니메이션을 루핑시키면 사용자에게 동적이고 흥미로운 UI를 구현하는 데 도움이 될 것입니다.

참고 자료: Apple Developer Documentation - Core Animation Programming Guide