[swift] Swift Core Animation의 육각형 변화 애니메이션

UIKit의 Core Animation 프레임워크를 사용하면 다양한 애니메이션 효과를 구현할 수 있습니다. 이 중에서 육각형을 변화시키는 애니메이션을 구현하는 예제를 살펴보겠습니다.

1. CALayer와 UIBezierPath 생성하기

먼저, 육각형 모양의 CALayerUIBezierPath를 생성합니다. 이 육각형은 CAShapeLayer를 사용하여 그립니다.

import UIKit

let hexagonLayer = CAShapeLayer()
hexagonLayer.path = hexagonPath.cgPath
hexagonLayer.fillColor = UIColor.red.cgColor
hexagonLayer.strokeColor = UIColor.black.cgColor

let hexagonPath = UIBezierPath()
let radius = 100.0
let angle = CGFloat(2 * Double.pi) / 6.0

let startPoint = CGPoint(x: centerX + radius * cos(0), y: centerY + radius * sin(0))
hexagonPath.move(to: startPoint)

for i in 1...6 {
    let x = centerX + radius * cos(CGFloat(i) * angle)
    let y = centerY + radius * sin(CGFloat(i) * angle)
    let point = CGPoint(x: x, y: y)
    hexagonPath.addLine(to: point)
}

hexagonPath.close()

2. 애니메이션 설정하기

다음으로, 육각형 변화 애니메이션을 설정합니다. CABasicAnimation을 사용하여 육각형의 path 속성을 변경하여 변화시킵니다.

let animation = CABasicAnimation(keyPath: "path")
animation.duration = 2.0
animation.toValue = newHexagonPath.cgPath
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)

hexagonLayer.add(animation, forKey: "hexagonAnimation")
hexagonLayer.path = newHexagonPath.cgPath

3. 뷰에 추가하기

마지막으로, 애니메이션을 적용할 뷰에 hexagonLayer를 추가합니다. 뷰 컨트롤러의 viewDidLoad() 메서드나 적절한 위치에서 다음과 같이 작성합니다.

self.view.layer.addSublayer(hexagonLayer)

결과 확인하기

위의 코드를 실행하면 육각형이 변화하는 애니메이션을 확인할 수 있습니다. hexagonLayerpath 속성을 변경하여 애니메이션을 제어할 수 있습니다.

[참고 자료]