본문 바로가기
Swift

터치로 그림그리기

by 루에 2015. 10. 23.
반응형

커스텀뷰를 활용한다.


UIView를 상속한 커스텀뷰에 drawRect()를 오버라이딩 한다. 그 외에는 방법이 여러가지가 있겠지만 touchBegan(), touchMoved()를 오버라이딩해서 시작 포인트를 잡고 이동 포인트를 잡은 뒤 UIBezierPath()에 담고, drawRect()에서 그린다.

코드는 아래와 같다.


DrawingView.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 
class DrawingView: UIView {
 
    var path = UIBezierPath()
    
    override func drawRect(rect: CGRect) {
        print("drawRect")
        path.stroke()
    }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = touches.first!
        let point = touch.locationInView(self)
        path.moveToPoint(point)
        
        print("touch began")
    }
 
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = touches.first!
        
        // 이동한 좌표까지 직선 그리기 경로 추가
        let point = touch.locationInView(self)
        path.addLineToPoint(point)
        
        // 다시 그리기
        self.setNeedsDisplay()
        print("touch moved")
    }
}
 

cs


ViewController.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
class ViewController: UIViewController {
 
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let drawView = DrawingView()
        drawView.backgroundColor = UIColor.whiteColor()
        drawView.frame = self.view.frame
        self.view.addSubview(drawView)
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
 
cs



커스텀뷰를 코드로 넣었기 때문에 따로 스토리보드를 작성하지 않는다.

반응형

댓글