How to set antialiasing on or off in a SwiftUI Canvas

101 views Asked by At

How do I turn antialiasing on or off in a SwiftUI Canvas?

struct CanvasView: View {
    var body: some View {
        Canvas { context, size in
            // CGContextSetShouldAntialias(context, false);
        }
    }
}
1

There are 1 answers

3
Sweeper On BEST ANSWER

There is no "global" switch in GraphicsContext that turns antialiasing on and off. Instead antialiasing can be controlled individually for each draw operation that takes a FillStyle. You can specify whether you want antialiasing when creating the FillStyle.

For example:

context.fill(
    somePath, with: .color(someColor), 
    fillStyle: .init(antialiased: false)
)

Otherwise, you can always get a CGContext and work with the CGContext APIs instead.

context.withCGContext { cgContext in
    cg.setShouldAntialias(false)
    // do the rest of your drawing here...
}

The stroking APIs don't take a FillStyle, so if you want to configure antialiasing for those, you will need to use the CGContext APIs, or convert the stroking operation to a fill operation, by using strokedPath:

let pathToStroke: Path = ...
let strokeStyle = StrokeStyle(...)
context.fill(path.strokedPath(strokeStyle), with: someColor, style: FillStyle(antialiased: false))