[swift] Swift Core Graphics로 터치 이벤트 처리하기
Swift에서 Core Graphics를 사용하여 터치 이벤트를 처리하는 방법에 대해 알아보겠습니다.
터치 이벤트 감지
터치 이벤트를 감지하기 위해서는 UIView
클래스를 서브클래싱하고 해당 뷰의 draw(_:)
메서드를 오버라이드해야 합니다.
import UIKit
class TouchableView: UIView {
override func draw(_ rect: CGRect) {
// 캔버스 초기화 및 그리기
let context = UIGraphicsGetCurrentContext()
context?.setLineWidth(2.0)
context?.setStrokeColor(UIColor.red.cgColor)
context?.move(to: CGPoint(x: 10, y: 10))
context?.addLine(to: CGPoint(x: 50, y: 50))
context?.strokePath()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// 터치 이벤트 발생 시 처리 로직
// 예: 터치한 지점에 점 그리기
if let touchPoint = touches.first?.location(in: self) {
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(UIColor.blue.cgColor)
context?.addArc(center: touchPoint, radius: 5.0, startAngle: 0, endAngle: CGFloat(2 * Double.pi), clockwise: true)
context?.fillPath()
}
setNeedsDisplay()
}
}
TouchableView
클래스는 UIView
를 상속하고 draw(_:)
메서드를 오버라이드하여 캔버스에 그릴 내용을 정의합니다. 또한 touchesBegan(_:with:)
메서드를 오버라이드하여 터치 이벤트를 처리하는 로직을 작성하였습니다.
TouchableView 사용하기
TouchableView
를 사용하여 터치 이벤트를 처리하는 방법은 아래와 같습니다.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let touchableView = TouchableView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
touchableView.backgroundColor = .white
view.addSubview(touchableView)
}
}
ViewController
클래스에서 TouchableView
를 생성하고 화면에 추가합니다.
이제 Core Graphics를 사용하여 터치 이벤트를 처리하는 방법에 대해 알아보았습니다. 다양한 그래픽 처리에 활용할 수 있는 기술입니다.
부가적인 질문이 있으시면 언제든지 물어봐주세요!