Skip to content

Instantly share code, notes, and snippets.

@swhitty
Created March 27, 2019 23:41
Show Gist options
  • Save swhitty/f2cb295160cb4885c7df0c67630c3d31 to your computer and use it in GitHub Desktop.
Save swhitty/f2cb295160cb4885c7df0c67630c3d31 to your computer and use it in GitHub Desktop.
extension CGPattern {
static func make(bounds: CGRect,
matrix: CGAffineTransform,
step: CGSize,
tiling: CGPatternTiling,
isColored: Bool,
draw: @escaping (CGContext) -> Void) -> CGPattern {
let drawPattern: CGPatternDrawPatternCallback = { info, ctx in
let box = Unmanaged<Box>.fromOpaque(info!).takeUnretainedValue()
box.closure(ctx)
}
let releaseInfo: CGPatternReleaseInfoCallback = { info in
Unmanaged<Box>.fromOpaque(info!).release()
}
var callbacks = CGPatternCallbacks(version: 0,
drawPattern: drawPattern,
releaseInfo: releaseInfo)
return CGPattern(info: Unmanaged.passRetained(Box(draw)).toOpaque(),
bounds: bounds,
matrix: matrix,
xStep: step.width,
yStep: step.height,
tiling: tiling,
isColored: isColored,
callbacks: &callbacks)!
}
private final class Box {
let closure: (CGContext) -> Void
init(_ closure: @escaping (CGContext) -> Void) {
self.closure = closure
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment