How can I use the drawing code generated by PaintCode with a CALayer?

How can I use the drawing code generated by PaintCode with a CALayer?

CALayer's delegate

You can use a delegate object to provide and update layer content when needed. If your delegate implements the displayLayer: method, you are responsible for creating a bitmap and assigning it to the layer's contents property.

If your delegate implements the drawLayer(_:, inContext:) (Objective-C: drawLayer:inContext:) method, CoreAnimation provides the context and you just need to call your drawing method from StyleKit (don't forget to call UIGraphicsPushContext(context) and UIGraphicsPopContext() before and after calling StyleKit drawing method).

// Swift
override func drawLayer(layer: CALayer, inContext ctx: CGContext)
{
    UIGraphicsPushContext(ctx)
    StyleKit.drawMyCanvas()
    UIGraphicsPopContext()
}
// Objective-C
- (void)drawLayer:(CALayer *)layer inContext: (CGContextRef)ctx
{	
	UIGraphicsPushContext(ctx);
    [StyleKit drawMyCanvas];
	UIGraphicsPopContext();
}

You can also do this for Mac targets:

// Swift 4
func draw(_ layer: CALayer, in ctx: CGContext) {
    NSGraphicsContext.saveGraphicsState()
    let context = NSGraphicsContext(cgContext: ctx, flipped: false)
    NSGraphicsContext.current = context
    StyleKit.drawMyCanvas()
    NSGraphicsContext.restoreGraphicsState()
}
// Swift 3
func draw(_ layer: CALayer, in ctx: CGContext) {
    NSGraphicsContext.saveGraphicsState()
    let context = NSGraphicsContext(cgContext: ctx, flipped: false)
    NSGraphicsContext.setCurrent(context)
    StyleKit.drawMyCanvas()
    NSGraphicsContext.restoreGraphicsState()
}
// Objective-C
- (void)drawLayer: (CALayer*)layer inContext: (CGContextRef)ctx
{
    [NSGraphicsContext saveGraphicsState];
    NSGraphicsContext* context = [NSGraphicsContext graphicsContextWithCGContext: ctx flipped: NO];
    [NSGraphicsContext setCurrentContext: context];

    [StyleKit drawMyCanvas];

    [NSGraphicsContext restoreGraphicsState];
}

Please, check out the example project and drawLayer(_:inContext:) (Objective-C: drawLayer:inContext:) method in EXApertureView. The EXApertureView is also the delegate of the EXApertureLayer subclass of CALayer.

CALayer subclass

You can override layer's display method and use it to set the contents property of the layer directly. You are responsible for creating the CGImageRef to be assigned to the contents property.

Alternatively, you can override layer's drawInContext: method and use it to draw into the provided graphics context:

// Swift
override func drawInContext(ctx: CGContext) 
{
    UIGraphicsPushContext(ctx)
    StyleKit.drawMyCanvas()
    UIGraphicsPopContext()
}
// Objective-C
- (void)drawInContext: (CGContextRef)ctx
{	
    UIGraphicsPushContext(ctx);
    [StyleKit drawMyCanvas];
    UIGraphicsPopContext();
}

Please, check out the example project and the EXLayer.