Instance Method

draw(_:in:)

Tells the delegate to implement the display process using the layer's CGContext.

Declaration

optional func draw(_ layer: CALayer, in ctx: CGContext)

Parameters

layer

The layer whose contents need to be drawn.

ctx

The graphics context to use for drawing. The graphics context incorporates the appropriate scale factor for drawing to the target screen.

Discussion

The draw(_:in:) method is called when the layer is marked for its content to be reloaded, typically with the setNeedsDisplay() method. It is not called if the delegate implements the display(_:) method. You can use the context to draw vectors, such as curves and lines, or images with the draw(_:in:byTiling:) method.

Listing 1 shows how you can create a class named LayerDelegate that implements CALayerDelegate and sets it as a layer's (named sublayer) delegate. When setNeedsDisplay() is called on sublayer, the delegate's draw(_:in:) method draws an ellipse fitting the bounding box of the layer using the boundingBoxOfClipPath function.

Listing 1

Drawing to a layer's graphics context

let delegate = LayerDelegate()
    
lazy var sublayer: CALayer = {
    let layer = CALayer()
    
    layer.delegate = self.delegate
    
    return layer
}()
    
// sublayer.setNeedsDisplay()
    
class LayerDelegate: NSObject, CALayerDelegate {
    func draw(_ layer: CALayer, in ctx: CGContext) {
        ctx.addEllipse(in: ctx.boundingBoxOfClipPath)
        ctx.strokePath()
    }
}

See Also

Providing the Layer's Content

func display(CALayer)

Tells the delegate to implement the display process.

func layerWillDraw(CALayer)

Notifies the delegate of an imminent draw.

Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software