<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Durymanov Andrei on Medium]]></title>
        <description><![CDATA[Stories by Durymanov Andrei on Medium]]></description>
        <link>https://medium.com/@adurymanov?source=rss-6612884d1945------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FcIjmW-ADBJJWOo5lHLHeg.jpeg</url>
            <title>Stories by Durymanov Andrei on Medium</title>
            <link>https://medium.com/@adurymanov?source=rss-6612884d1945------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 05:52:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adurymanov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AsyncCanvas in SwiftUI]]></title>
            <link>https://medium.com/@adurymanov/asynccanvas-in-swiftui-a80deea7f1b9?source=rss-6612884d1945------2</link>
            <guid isPermaLink="false">https://medium.com/p/a80deea7f1b9</guid>
            <category><![CDATA[canvas]]></category>
            <category><![CDATA[optimisation]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Durymanov Andrei]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 11:54:37 GMT</pubDate>
            <atom:updated>2023-06-27T11:54:37.934Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Most of the text in this article was generated with ChatGPT. You can use it as a reference or as wrappers for code snippets and measurements, which form the core value of the article.</em></blockquote><p><a href="https://github.com/adurymanov/Article-AsyncCanvasMaterials">Repository with materials using in this article</a></p><p><a href="https://github.com/adurymanov/AsyncCanvas">Repository with AsyncCanvas</a></p><h3>Introduction</h3><p>The advent of SwiftUI brought a refreshing approach to UI development on Apple platforms. It’s declarative, it’s concise, and it’s powerful. However, when it comes to intensive graphical tasks, it can sometimes meet its limits. Traditional methods of rendering on the SwiftUI Canvas can lead to less-than-optimal performance and hinder the smoothness of the user interface.</p><p>The aim of this article is to illustrate an alternative approach to SwiftUI Canvas rendering—AsyncCanvas. This method allows for asynchronous rendering, which can enhance performance and provide a more fluid user experience, especially when handling demanding graphics tasks.</p><h3>Test Environment</h3><p>For our testing setup, we use Xcode version 13.0 or later and target iOS 15.0 or later to leverage the full potential of SwiftUI and Apple’s new concurrency features. Our test environment is encapsulated in a View called Environment.</p><p>Our Environment renders a number of lines based on the value state variable. The lines, drawn within a render method, have random start and end points and random colors. This approach allows us to test the performance impact of rendering a large number of complex graphical objects in SwiftUI.</p><pre>struct Environment&lt;R: View&gt;: View {<br><br>    @State var value = 1.0<br><br>    let benchmark: Double = 50_000<br><br>    let render: (Double) -&gt; R<br><br>    var body: some View {<br>        VStack {<br>            render(value)<br>            Button(&quot;Show lines&quot;) {<br>                value = benchmark<br>            }<br><br>            Slider(value: $value, in: 1...100_000)<br>        }<br>        .padding()<br>    }<br><br>}</pre><p>The Environment struct is designed with two main components for performance testing:</p><ol><li>A <strong>Slider</strong>: This allows for a smooth transition between different Double values, which dynamically update the rendered view. It is used to test UI smoothness and observe the impact of varying graphical intensity on the user interface&#39;s performance.</li><li>A <strong>Button</strong>: The “Show lines” button is used to instantly set the value to the pre-determined benchmark value. This simulates a high-intensity rendering scenario and allows us to benchmark how different rendering techniques handle such conditions.</li></ol><h3>Basic ways to implement Canvas</h3><h3>Shapes</h3><p>Shapes are the building blocks of SwiftUI’s drawing system. They can be stroked, filled, and used in other drawing operations.</p><pre>struct RenderShapes: View {<br>    <br>    let value: Double<br>    <br>    var body: some View {<br>        ZStack {<br>            ForEach(0...Int(value), id: \\.self) { _ in<br>                Path { path in<br>                    path.move(to: .random)<br>                    path.addLine(to: .random)<br>                }<br>                .stroke(<br>                    Color.random,<br>                    style: StrokeStyle(<br>                        lineWidth: 1,<br>                        lineCap: .round,<br>                        lineJoin: .round<br>                    )<br>                )<br>            }<br>        }<br>        .drawingGroup()<br>    }<br>    <br>}</pre><p>This is implementation of render view using shapes.</p><h3>Canvas</h3><p>Canvas is a SwiftUI view that you can use to draw custom graphics, charts, or other visualisations directly with a flexible interface.</p><pre>struct RenderCanvas: View {<br>    <br>    let value: Double<br>    <br>    var body: some View {<br>        Canvas(rendersAsynchronously: true) { context, _ in<br>            for _ in 0...Int(value) {<br>                let path = Path {<br>                    $0.move(to: .random)<br>                    $0.addLine(to: .random)<br>                }<br>                context.stroke(<br>                    path,<br>                    with: .color(.random),<br>                    style: StrokeStyle(lineWidth: 1)<br>                )<br>            }<br>        }<br>    }<br>}</pre><p>This is implementation of render view using Canvas.</p><h3>Measurements of Basic Implementation</h3><figure><img alt="Shapes render of 50000 lines" src="https://cdn-images-1.medium.com/max/1024/1*9IdaPT6FBWdo-d6sOQlmdA.png" /><figcaption>Shapes render of 50000 lines</figcaption></figure><p>As we have seen, rendering complex objects with shapes can cause significant hang-ups in the user interface. This is expected as these components need to synchronise with other views, necessitating their rendering on the main thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFjTgtCkpsl62hfVt6v6cQ.png" /><figcaption>Canvas render of 50000 lines</figcaption></figure><p>Canvas provides a more efficient solution for this kind of rendering. It uses far fewer resources to render the final image, but it can still cause minor hang-ups. The reason for these slowdowns is that the render method runs synchronously with the main thread. This method execution is labelled as &quot;canvas_render&quot; in the &quot;Points of Interests&quot; section.</p><p>As result, the basic implementation works well for simple and moderate complexity tasks, providing high-quality rendering with reasonable performance. However, performance might degrade for more complex tasks due to the synchronous nature of the rendering.</p><h3>AsyncCanvas Solution</h3><p>The key difference in the AsyncCanvas solution lies in the render method running asynchronously. This means the rendering of the canvas does not block the main thread, and the user interface remains responsive even during complex rendering tasks.</p><pre>public struct AsyncCanvas&lt;Processor: RenderProcessor&gt;: View {<br>    <br>    typealias ProcessorTask = RenderTask&lt;Processor.Context&gt;<br>    <br>    @State var image: Image?<br>    <br>    @State var renderTask: Task&lt;Void, Never&gt;?<br>    <br>    private let render: ProcessorTask<br>    <br>    private let processor: Processor<br><br>    public var body: some View {<br>        GeometryReader { proxy in<br>            ZStack {<br>                if let image { image }<br>            }<br>            .onChange(of: render) { newRender in<br>                render(size: proxy.size, task: render)<br>            }<br>            .task {<br>                render(size: proxy.size, task: render)<br>            }<br>        }<br>    }<br>    <br>    func render(size: CGSize, task: ProcessorTask) {<br>        renderTask?.cancel()<br>        <br>        renderTask = Task.detached {<br>            await render(size: size, task: task)<br>        }<br>    }<br>    <br>    func render(size: CGSize, task: ProcessorTask) async {<br>        guard let image = await processor.render(size: size, render: task)<br>        else {<br>            return<br>        }<br>        guard !Task.isCancelled else {<br>            return<br>        }<br>        await MainActor.run {<br>            self.image = image<br>        }<br>    }<br>    <br>}</pre><p>AsyncCanvas is a custom SwiftUI view that mimics the Canvas view but with a twist — it handles the rendering asynchronously. This way, it avoids blocking the main thread, improving the user interface’s overall responsiveness.</p><p>Processor could be implemented using Core Graphics framework.</p><pre>public final actor CGRenderProcessor: RenderProcessor {<br>    <br>    public typealias Context = CGContext<br>    <br>    public func render(size: CGSize, render: RenderTask&lt;Context&gt;) async -&gt; Image? {<br>        try? await Self.render(size: size, render: render)<br>    }<br><br>}<br><br>private extension CGRenderProcessor {<br>    <br>    enum RenderError: Error {<br>        case taskCanceled<br>        case uiImageRenderFiled<br>    }<br><br>    static func render(size: CGSize, render: RenderTask&lt;CGContext&gt;) async throws -&gt; Image {<br>        defer {<br>            UIGraphicsEndImageContext()<br>        }<br>        <br>        try checkCancelation()<br>        <br>        UIGraphicsBeginImageContextWithOptions(size, false, .zero)<br>        <br>        try checkCancelation()<br>        <br>        let context = UIGraphicsGetCurrentContext()!<br>        <br>        try checkCancelation()<br>        <br>        await render.task(context, size)<br>        <br>        try checkCancelation()<br>        <br>        guard let uiImage = UIGraphicsGetImageFromCurrentImageContext() else {<br>            throw RenderError.uiImageRenderFiled<br>        }<br>        <br>        try checkCancelation()<br>        <br>        return Image(uiImage: uiImage)<br>    }<br>    <br>    static func checkCancelation() throws {<br>        if Task.isCancelled {<br>            throw RenderError.taskCanceled<br>        }<br>    }<br>    <br>}</pre><p>The render method in CGRenderProcessor starts by beginning a new CGContext. It then executes the render task within this context. Once the task is complete, the resulting image is rendered into a UIImage and returned as an Image view.</p><h3>Example of usage</h3><pre>struct RenderAsyncCanvas: View {<br>    <br>    let value: Double<br>    <br>    var body: some View {<br>        AsyncCanvas { context, _ in<br>            for _ in 0...Int(value) {<br>                guard !Task.isCancelled else {<br>                    return<br>                }<br>                context.move(to: .random)<br>                context.addLine(to: .random)<br>                context.setStrokeColor(.random)<br>                context.strokePath()<br>            }<br>        }<br>    }<br>    <br>}</pre><p>The usage of AsyncCanvas is similar to standard SwiftUI Canvas, but there are two key differences. First, the render method in AsyncCanvas is asynchronous, and second, the context used is CGContext.</p><h3>Measurements of AsyncCanvas</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JnUjpPzCQv96H0kEbUcg2w.png" /><figcaption>AsyncCanvas render 50000 lines</figcaption></figure><p>In the “Points of Interests” section, the “cg_render” label highlights the execution of the render method. The AsyncCanvassolution does require more time to handle resource-intensive rendering tasks. However, all these calculations are processed on background threads, thereby preventing any potential interface freezes or hangs.</p><h3>Conclusion</h3><p>While the default SwiftUI solutions offer an excellent starting point for most tasks, they have certain limitations when it comes to complex, resource-intensive operations. But fear not, these limitations can be bypassed with custom solutions such as AsyncCanvas.</p><p>Remember, SwiftUI is a powerful tool, but like any tool, it’s most effective when used in the right way. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a80deea7f1b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>