I am trying to translate an old code of mine from objective-c to swift.
But I get the following error on self.image.drawInRect():
fatal error: Can't unwrap Optional.None
I have this class called Canvas, it is a subclass of UIImageView and its set on storyboard and its initialized on my only ViewController :
init(coder aDecoder: NSCoder!) {
pref = NSUserDefaults.standardUserDefaults()
currentPlay = Play()
canvas = Canvas(coder: aDecoder)
super.init(coder: aDecoder)
}
This is my Canvas.Swift
import UIKit
class Canvas: UIImageView {
var path:UIBezierPath = UIBezierPath()
var drawColor:UIColor = UIColor.greenColor()
var lastLocation:CGPoint = CGPoint()
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
// handling touches
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
let touch:UITouch = touches.anyObject() as UITouch
lastLocation = touch.locationInView(self.superview)
}
override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
let touch:UITouch = touches.anyObject() as UITouch
let location = touch.locationInView(self.superview)
UIGraphicsBeginImageContext(self.frame.size)
self.image.drawInRect(self.frame)
path = UIBezierPath()
path.lineWidth = 8;
path.lineCapStyle = kCGLineCapRound;
drawColor.setStroke()
path.moveToPoint(CGPointMake(lastLocation.x, lastLocation.y))
path.addLineToPoint(CGPointMake(location.x, location.y))
path.stroke()
self.image = UIGraphicsGetImageFromCurrentImageContext();
lastLocation = location
path.closePath()
UIGraphicsEndImageContext();
}
override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
// nothing yet
}
}
ps: if I remove the drawInRect line I can get the drawing for the moment if goes through the touchedMoved... but since the context gets reset, it does not persist on the image