[swift] Swift Core Animation을 이용한 터치 이벤트 애니메이션

터치 이벤트를 사용하여 애니메이션을 만들기 위해 Core Animation 프레임워크를 사용할 수 있습니다. Core Animation은 iOS 및 macOS에서 사용되는 강력한 그래픽 렌더링 엔진으로, 높은 성능과 부드러운 애니메이션을 제공합니다.

이번 예제에서는 Swift에서 Core Animation을 이용하여 터치 이벤트에 반응하는 애니메이션을 만들어 보겠습니다.

요구사항

프로젝트 설정

  1. Xcode를 열고 “New Project”를 선택하여 새로운 프로젝트를 생성합니다.
  2. “Single View App” 템플릿을 선택하고 필요한 정보를 입력한 뒤, 프로젝트를 생성합니다.
  3. 생성된 프로젝트에서 ViewController.swift 파일을 엽니다.

코드 구현

  1. ViewController.swift 파일을 열고 다음 코드를 추가합니다:
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let animationView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        animationView.backgroundColor = UIColor.red
        self.view.addSubview(animationView)
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
        animationView.addGestureRecognizer(tapGesture)
    }
    
    @objc func handleTap(sender: UITapGestureRecognizer) {
        let animation = CABasicAnimation(keyPath: "transform.scale")
        animation.fromValue = 1.0
        animation.toValue = 2.0
        animation.duration = 0.5
        animation.repeatCount = 1
        animation.autoreverses = true
        
        sender.view?.layer.add(animation, forKey: "scale")
    }
}
  1. handleTap(sender:) 메서드는 터치 이벤트를 처리하고 애니메이션을 적용합니다. 애니메이션은 CABasicAnimation을 사용하여 구현되었으며, transform.scale 속성을 변경하여 뷰의 크기를 조절합니다.

실행 및 확인

프로젝트를 빌드하고 시뮬레이터 또는 실제 기기에서 실행해 보면 애니메이션이 적용된 뷰가 터치 이벤트에 응답하는 것을 확인할 수 있습니다. 터치할 때마다 뷰의 크기가 2배로 확대되었다가 다시 원래 크기로 돌아가는 애니메이션이 재생됩니다.

결론

Swift Core Animation을 이용하여 터치 이벤트에 반응하는 애니메이션을 만들어 보았습니다. Core Animation은 iOS 및 macOS 앱에서 다양한 애니메이션 효과를 적용하는 데 유용한 프레임워크입니다. 이 예제를 참고하여 앱에서 터치 이벤트에 따른 다양한 애니메이션을 구현해보세요.