drawLayer:inContext 未显示绘图

drawLayer:inContext not displaying drawing

我正在尝试在 UIView subclass on Xcode 8, Swift 3 中绘制一个蓝色圆圈。 Cocoa Touch 文件,我在 Storyboard 中用作 class 对象的 View,我写了以下代码,但圆圈未显示:

import UIKit

class testView: UIView {
    override func draw(_ layer: CALayer, in ctx: CGContext) {
        ctx.addEllipse(in: CGRect(x: 0, y: 0, width: 100, height: 100))
        ctx.setFillColor(UIColor.blue.cgColor)
        ctx.fillPath()
    }
}

UIKit这个版本也不显示圆圈:

override func draw(_ layer: CALayer, in ctx: CGContext) {
    UIGraphicsPushContext(ctx)
    let p = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))
    UIColor.blue.setFill()
    p.fill()
    UIGraphicsPopContext()
}

我做错了什么?

我正在处理你的问题,这是我的结果,首先你需要获得 CurrentGraphicsContent,如果你不这样做,你将无法绘制任何东西,所以请尝试使用此代码

override func draw(_ rect: CGRect) {
    super.draw(rect)

    if let ctx = UIGraphicsGetCurrentContext() {
        ctx.setFillColor(UIColor.blue.cgColor)
        ctx.addEllipse(in: CGRect(x: 0, y: 0, width: 100, height: 100))
        ctx.fillPath()

        UIGraphicsEndImageContext()
    }
    // Drawing code
}

希望对你有帮助