pistacchio
pistacchio

Reputation: 58953

Draw shapes with SwiftUI

So, I want to use the accelerated graphics engine and hence draw some shapes with CALayer / CAShaperLayer. I want a view of 100x100 with a rounded rectangle of 50x50. Mind that this is in a MacOS environment, not iOS. I have the following code that that doesn't work:


struct KeyboardView2: NSViewRepresentable {
    func makeNSView(context: Context) -> NSView {
        var view = NSView(frame: NSRect(x: 0, y: 0, width: 100, height: 100))
        
        var shapeLayer = CAShapeLayer()
        shapeLayer.frame = NSRect(x: 0, y: 0, width: 100, height: 100)
        
        let path = NSBezierPath(roundedRect: NSRect(x: 0, y: 0, width: 50, height: 50), xRadius: 10, yRadius: 10)
        NSColor.red.setFill()
        NSColor.blue.setStroke()
        path.stroke()
        
        view.layer = CALayer()
        view.layer!.frame = NSRect(x: 0, y: 0, width: 100, height: 100)
        view.layer!.addSublayer(shapeLayer)
        return view
    }
            
    func updateNSView(_ nsView: NSViewType, context: Context) {
        
    }
}

Amy idea? Thanks

Upvotes: 0

Views: 266

Answers (1)

DaveHowell
DaveHowell

Reputation: 1264

You have your drawing code in the makeNSView method. You want to put it in the draw method.

Upvotes: 1

Related Questions