Etch A Sketch

The previous touch-sensitive apps (Touch, Hit) moved a little view inside a bigger view. This app has only one view. Instead of moving views around, it accumulates more and more information about the touch in a variable of type CGMutablePathRef.

Source code in Etch.zip

  1. Class AppDelegate.
  2. Class ViewController.
  3. Class View. I added the CMutablePathRef property, the init that takes an NSCoder, touchesBegain(_:withEvent:), and drawRect(_:).

We saw a CGMutablePathRef when we filled and stroked the triangle in Japan. The View object of this app contains contains a CGMutablePathRef named path, containing straight lines connecting points. The touchesBegan(_:withEvent:) and touchesMoved(_:withEvents:) methods of the View make the path longer.

Things to try

  1. Erase the drawing when the app is hidden (e.g., when the Home button is pressed) and uncovered. Add the following method to class View in the file View.swift. You will have to create the path property of the View with var instead of let.
    	func clearPath() {
    		path = CGPathCreateMutable();	//empty out the path
    		setNeedsDisplay();
    	}
    
    Call clearPath in the applicationDidEnterBackground(_:) method of the application delegate in the file AppDelegate.swift.
    		let viewController: ViewController = window?.rootViewController as ViewController;
    		let view: View = viewController.view as View;
    		view.clearPath();
    

  2. When we learn about buttons, come back to this app and make an erase button.