1
votes

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

1
Is self.image non-nil? - rdelmar
I dont set an image at any time. So I think so. - Andre Cytryn
Adding an image to the canvas works fine... but if the image has a different size, the canva go wild... - Andre Cytryn

1 Answers

2
votes

UIImageView is generally init'd with an image - but in your case you're unarchiving it and assuming the image property holds a valid image. Since the image property is implicitly unwrapped (it's defined as var image: UIImage!) it does not give you a compile time error, and instead crashes at runtime.

To unwrap the image and use drawInRect when the image is available replace self.image.drawInRect(self.frame) with

if let image = self.image {
    image.drawInRect(self.frame)
}