CGContext 初始化后不绘制

CGContext not drawing after initialising

我正在尝试在 UIView draw(_:) 中创建自己的 CGContext。这里:

    override func draw(_ rect: CGRect) {
        //let ctx = UIGraphicsGetCurrentContext()
        let width = Int(rect.size.width)
        let height = Int(rect.size.height)
        let bytesPerPixel = 4
        let bytesPerRow = bytesPerPixel * width
        let data = UnsafeMutableRawPointer.allocate(byteCount: bytesPerRow * height/*727080*/, alignment: 8)
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        guard let ctx = CGContext(data: data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue) else {
            return
        }
        ctx.setStrokeColor(UIColor.orange.cgColor)
        ctx.setLineWidth(3.0)
        ctx.stroke(rect)
    }

并且视图在显示时没有勾勒出轮廓,而使用当前上下文自然地工作(显示边界边框笔画):

    override func draw(_ rect: CGRect) {
        guard let ctx = UIGraphicsGetCurrentContext() else {
            return
        }
        ctx.setStrokeColor(UIColor.orange.cgColor)
        ctx.setLineWidth(3.0)
        ctx.stroke(rect)
    }

我已经按照 CGContext init 方法的 swift 头文件中的描述进行操作。这与获取当前上下文的功能不同的原因是什么,因为我似乎使用当前视图中的位图信息集。

这是一个创建屏幕外内容的简单演示,用于准备某些内容(可能很重,所以不会阻塞 UI)以呈现在视图中

class ViewWithOffscreenDrawing: UIView {
    private var offscreenImage: CGImage? = nil

    override func draw(_ rect: CGRect) {
        if offscreenImage == nil { // image not ready
            DispatchQueue.global(qos: .background).async { // draw offscreen
                let image = renderSomething(of: rect.size)
                DispatchQueue.main.async { [weak self] in
                    self?.offscreenImage = image
                    self?.setNeedsDisplay()
                }
            }
            return
        }

        // image has prepared - just draw on screen
        UIGraphicsGetCurrentContext()?.draw(offscreenImage!, in: rect)
    }
}

func renderSomething(of size: CGSize) -> CGImage? {
    let bitsPerComponent = 8
    let bytesPerRow = Int(size.width) * 4
    let colorSpace = CGColorSpace(name: CGColorSpace.genericRGBLinear)!

    let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height),
        bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow,
        space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)

    // >>> draw anything heavy in background context

    context?.setFillColor(gray: 1, alpha: 1)
    context?.fill(CGRect(origin: .zero, size: size))
    context?.setFillColor(UIColor.red.cgColor)
    context?.fillEllipse(in: CGRect(origin: .zero, size: size))

    // <<<

    return context?.makeImage() // generated result
}