[swift] Swift Core Graphics를 사용하여 그래픽 요소 애니메이션화하기
Swift에서 Core Graphics 프레임워크를 사용하여 그래픽 요소를 그리고 애니메이션화하는 방법을 알아보겠습니다.
목차
- Core Graphics 개요
- 그래픽 요소 그리기
- 애니메이션 추가
- 예제 코드
- 참고 자료
1. Core Graphics 개요
Core Graphics는 iOS 및 macOS 애플리케이션에서 2D 그래픽을 그리기 위한 프레임워크입니다. 이를 이용하면 직접 그림을 그릴 수 있고, 그래픽 요소를 애니메이션화할 수 있습니다.
2. 그래픽 요소 그리기
Core Graphics를 사용하여 뷰의 draw(_:)
메서드를 오버라이드하고, 콘텍스트에 원하는 그래픽을 그립니다. 이 메서드는 뷰가 그려질 때마다 호출됩니다.
3. 애니메이션 추가
그래픽 요소에 애니메이션을 추가하기 위해 UIView
애니메이션 블록을 사용합니다. 그래픽 요소의 속성을 변경하고 setNeedsDisplay
를 호출하여 뷰를 다시 그리도록 합니다.
4. 예제 코드
아래는 실제로 선 한 개를 애니메이션화하는 간단한 예제 코드입니다.
import UIKit
class CustomView: UIView {
var lineWidth: CGFloat = 5.0
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
context.setLineWidth(lineWidth)
context.setStrokeColor(UIColor.blue.cgColor)
context.move(to: CGPoint(x: 20, y: 20))
context.addLine(to: CGPoint(x: 100, y: 100))
context.strokePath()
}
func animateLine() {
UIView.animate(withDuration: 1.0) {
self.lineWidth = 10.0
self.setNeedsDisplay()
}
}
}
5. 참고 자료
- Core Graphics Framework - Apple Developer Documentation
- UIView - Apple Developer Documentation
- Swift.org - Swift Language Guide