Search code examples
iosswiftcocoaxcode8draw

drawLayer:inContext not displaying drawing


I'm trying to draw a blue circle inside a UIView subclass on Xcode 8, Swift 3. Inside a Cocoa Touch file that I'm using as the class for a View object in the Storyboard, I wrote the following code, but the circle is not displayed:

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

This version with UIKit doesn't display the circle neither:

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

What am I doing wrong?


Solution

  • I was working on your question and this are my results, first of all you need to get you CurrentGraphicsContent, if you don't do this, you can't draw anything, so try with this code

    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
    }
    

    I hope this helps you