'Swift. disable antialiasing when UIBezierPath append

I'd like to append UIBezierPath without antialiasing. Here is what I tried. testView's frame is 10x10

    let shadowLayer = CALayer()
    var path: UIBezierPath!
    
    shadowLayer.frame = testView.bounds
    path = UIBezierPath(rect: CGRect(x: 1, y: 1, width: 3, height: 3))
    shadowLayer.shadowPath = path.cgPath
    shadowLayer.shadowColor = UIColor.red.cgColor
    shadowLayer.shadowOffset = .init(width: 0, height: 0)
    shadowLayer.shadowOpacity = 1
    shadowLayer.shadowRadius = 0
    testView.layer.addSublayer(shadowLayer)

The red rectangle inside testView is 3x3, no problem.

But when I append another UIBezierPath.

    ...
    path = UIBezierPath(rect: CGRect(x: 1, y: 1, width: 3, height: 3))
    path.append(UIBezierPath(rect: CGRect(x: 5, y: 5, width: 3, height: 3)))
    ...

The red rectangles are getting antialiasing.

How do I disable antialiasing when appending UIBezierPath? Thanks.



Solution 1:[1]

You can create a new graphics context, set the shouldAntialias attribute to false and add the cgPath from your UIBezierPath to it. Or you can move it to draw(_:), get the current context and do the same.

https://developer.apple.com/documentation/appkit/nsgraphicscontext/1529486-shouldantialias

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lalo