UIGraphicsGetCurrentContext() 获取当前 CGContext 失败

问题描述

我在一本学习iOS 13编程的书上看到了一个例子。这个例子打算画一个如下图所示的箭头:

enter image description here

示例代码如下:

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()
    }
}

但是,在运行时,代码行 guard let con = UIGraphicsGetCurrentContext() else { return } 未能按预期生成 CGContext 实例。我不知道为什么会这样。您能否帮助解释原因并提出解决问题的建议?非常感谢!

解决方法

那是我的书和我的箭头,而您没有按照书中的说明进行操作。该示例告诉您位于 UIView 子类中,并且应从您的 draw(_:) 覆盖调用此代码。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...