Search code examples
iosswiftuigraphicscontext

UIGraphicsGetCurrentContext() failed to get the current CGContext


I came across an example in a book for learning iOS 13 programming.The example intends to draw an arrow like the one in the following picture:

enter image description here

The code for the example is as follows:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        drawArrow()
    }

    func drawArrow () {
        // obtain the current graphics context
        guard let con = UIGraphicsGetCurrentContext() else { return }
        // draw a black (by default) vertical line, the shaft of the arrow
        con.move(to: CGPoint(100, 100))
        con.addLine(to: CGPoint(100, 19))
        con.setLineWidth(20)
        con.strokePath()
        // draw a red triangle, the point of the arrow
        con.setFillColor(UIColor.red.cgColor)
        con.move(to: CGPoint(80, 25))
        con.addLine(to: CGPoint(120, 25))
        con.fillPath()
        // snap a triangle out of the shaft by drawing in Clear blend mode
        con.move(to: CGPoint(90, 101))
        con.addLine(to: CGPoint(100, 90))
        con.addLine(to: CGPoint(110, 101))
        con.setBlendMode(.clear)
        con.fillPath()
    }
}

However, when run, the line of code guard let con = UIGraphicsGetCurrentContext() else { return } failed to produce the CGContext instance as expected. I'm not sure why it is like that. Would you please help explain why and suggest a solution to the issue? Thank you very much!


Solution

  • That's my book and my arrow and you didn't follow the directions in the book. The example tells you to be in a UIView subclass and that this code should be called from your draw(_:) override.