Reputation: 53
I've found this code for drawing the line for MacOS app.
class Drawing: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let context = NSGraphicsContext.current?.cgContext;
context!.beginPath()
context!.move(to: CGPoint(x: 0.0, y: 0.0))
context!.addLine(to: CGPoint(x: 100.0, y: 100.0))
context!.setStrokeColor(red: 1, green: 0, blue: 0, alpha: 1)
context!.setLineWidth(1.0)
context!.strokePath()
}
override func viewDidLoad() {
super.viewDidLoad()
let dr = Drawing(frame: NSRect(x: 0, y: 0, width: 100, height: 100))
self.view.addSubview(dr)
}
How to change this code for circle? It's difficult for me to solve this problem. Help me, please.
Upvotes: 2
Views: 4813
Reputation: 190
Depending on the side of the circle, you can also do this:
class YourParentView: NSView {
// Create it as a view of its own
let circleView = NSView()
circleView.wantsLayer = true
circleView.layer?.cornerRadius = 7
//depending on the size, adjust this
//and that's it. Now it's a circle.
//Then just addict the style
circleView.layer?.backgroundColor = NSColor.green.cgColor
circleView.layer?.borderColor = NSColor.white.cgColor
//Be sure to add it to the parent view
self.view.addSubview(circleView)
}
Upvotes: 2
Reputation: 285079
The circle equivalent is
class Drawing: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let context = NSGraphicsContext.current!.cgContext
context.saveGState()
context.setFillColor(NSColor.red.cgColor)
context.fillEllipse(in: dirtyRect)
context.restoreGState()
}
}
or the classic NSBezierPath
way
class Drawing: NSView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let fillColor = NSColor.red
let path = NSBezierPath(ovalIn: dirtyRect)
fillColor.setFill()
path.fill()
}
}
Upvotes: 9