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
If your delegate implements the StyleKit (don't forget to call 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 EXApertureView. The EXApertureView is also the delegate of the EXApertureLayer subclass of CALayer.
CALayer subclass
You can override layer's CGImageRef to be assigned to the contents property.
Alternatively, you can override layer's
// 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.