Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CGContext with SwiftUI

Tags:

swift

swiftui

I want to use CGContext while using SwiftUI View. How to get current CGContext?

like image 382
swiftr sven Avatar asked Jul 30 '26 06:07

swiftr sven


1 Answers

In general you don't use Core Graphics inside of SwiftUI. However, if you have Core Graphics code that you want to use, it's fairly straightforward. You need to wrap a UIView and draw in there.

To include a UIView in a SwiftUI view hierarchy, use UIViewRepresentable. You can then include your Core Graphics code in drawRect as usual, and embed that in your SwiftUI.

Apple provides a tutorial on this in Interfacing with UIKit.

Note that SwiftUI itself doesn't expose a Core Graphics context. It's a declarative language that describes the view hierachy. You don't have access to the "actual" drawing objects. (And the actual drawing objects aren't promised to use CGContext internally, though most and possibly all do.)

like image 76
Rob Napier Avatar answered Aug 01 '26 23:08

Rob Napier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!