Created
February 20, 2024 09:19
-
-
Save ollieatkinson/f16438dad155a4aaee6f261956f484c9 to your computer and use it in GitHub Desktop.
Render to a CGContext directly from SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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