【问题标题】:UIGraphicsGetCurrentContext() failed to get the current CGContextUIGraphicsGetCurrentContext() 获取当前CGContext失败
【发布时间】:2021-06-18 22:14:05
【问题描述】:

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

示例代码如下:

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 实例。我不知道为什么会这样。您能否帮助解释原因并提出解决方案?非常感谢!

【问题讨论】:

    标签: ios swift uigraphicscontext


    【解决方案1】:

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

    【讨论】:

    • 请参阅github.com/mattneub/Programming-iOS-Book-Examples/blob/… 了解这方面的工作示例和所有书中的代码
    • 非常感谢@matt 的即时帮助!我很惊讶也很高兴能从本书的作者本人那里得到答案!很抱歉我只关注书中的代码sn-p,忘记查阅你提供的完整代码示例。阅读序言时翻页太快:)。再次感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 2017-05-10
    相关资源
    最近更新 更多