Skip to content

Instantly share code, notes, and snippets.

@ollieatkinson
Created February 20, 2024 09:19
Show Gist options
  • Save ollieatkinson/f16438dad155a4aaee6f261956f484c9 to your computer and use it in GitHub Desktop.
Save ollieatkinson/f16438dad155a4aaee6f261956f484c9 to your computer and use it in GitHub Desktop.
Render to a CGContext directly from SwiftUI
protocol CGContextRepresentable: View {
func draw(in context: CGContext, frame: CGRect)
}
extension CGContextRepresentable {
var body: some View { _CGContextView(draw: draw) }
}
private struct _CGContextView: UIViewRepresentable {
let draw: (CGContext, CGRect) -> Void
func makeUIView(context: Context) -> UIView { _DrawToContextView(draw: draw) }
func updateUIView(_ view: UIView, context: Context) { view.setNeedsDisplay() }
private class _DrawToContextView: UIView {
let draw: (CGContext, CGRect) -> Void
init(draw: @escaping (CGContext, CGRect) -> Void) {
self.draw = draw
super.init(frame: .zero)
self.backgroundColor = .clear
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
draw(context, rect)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment