Here is a way to render the shadow only. The way is background color, shadow color agnostic.
The gist is
- add a big horizontal offset to the
shadow
you want to render. So that the shadow is separated out from the shadow shape.
- Translate the context with a negative same horizontal offset, so that the shadow shape is moved out of the rendering area, and the shadow is moved back.
- Render normally, you will get the shadow rendering only.
Example code:
func normalShadowRendering() {
let context = UIGraphicsGetCurrentContext()!
// the shape, a triangle
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0, y: 32))
bezierPath.addLine(to: CGPoint(x: 16, y: 0))
bezierPath.addLine(to: CGPoint(x: 32, y: 32))
bezierPath.close()
// set shadow
context.setShadow(offset: CGSize(width: 4, height: 4), blur: 8.0, color: UIColor.black.cgColor)
// render the shape with shadow
context.addPath(bezierPath.cgPath)
UIColor.red.setStroke()
context.setLineWidth(4)
context.strokePath()
}
The rendering result is:
func shadowOnlyRendering() {
let context = UIGraphicsGetCurrentContext()!
// the shape, a triangle
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0, y: 32))
bezierPath.addLine(to: CGPoint(x: 16, y: 0))
bezierPath.addLine(to: CGPoint(x: 32, y: 32))
bezierPath.close()
// set shadow
// `drawingRect` is the canvas rect
// add the canvas width extra horizontal offset, so that
// shadow is separated out
context.setShadow(offset: CGSize(width: 4 + drawingRect.width, height: 4), blur: 8.0, color: UIColor.black.cgColor)
// compensate the extra horizontal offset added to the shadow
// so that the shadow is rendered at correct place, and the
// main shape is moved out of the canvas.
context.translateBy(x: -drawingRect.width, y: 0)
// render the shadow only
// shape is out of the canvas
context.addPath(bezierPath.cgPath)
UIColor.red.setStroke()
context.setLineWidth(4)
context.strokePath()
}
The rendering result is:
[[NSColor clearColor] GCColor]
– ReincarnateCGContextSetStrokeColorWithColor(context, [UIColor clearColor].CGColor);
– AgnosticismCGContextSetLineWidth(context, 0.0);
– Agnosticism