swiftr sven
swiftr sven

Reputation: 23

Using CGContext with SwiftUI

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

Upvotes: 2

Views: 2173

Answers (2)

zoha131
zoha131

Reputation: 1888

From iOS 15

Apple introduced new SwiftUI view named Canvas which provide GraphicsContext in closure.

GraphicsContext is SwiftUI equivalent of CGContext. You can even use existing drawing code that relies on Core Graphics primitives through the method named withCGContext(content:)

Upvotes: 5

Rob Napier
Rob Napier

Reputation: 299325

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.)

Upvotes: 5

Related Questions