在Swift中绘制一个圆圈(MacOS)

时间:2018-03-03 15:21:56

标签: swift macos cocoa draw geometry

我发现此代码用于绘制MacOS应用的行。

 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)
}

如何更改圈子的此代码?我很难解决这个问题。请帮帮我。

2 个答案:

答案 0 :(得分:3)

等效圆是

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()
    }   
}

或经典NSBezierPath方式

class Drawing: NSView {
    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        let fillColor = NSColor.red
        let path = NSBezierPath(ovalIn: dirtyRect)
        fillColor.setFill()
        path.fill()
    }
}

答案 1 :(得分:0)

根据圆的侧面,您也可以执行以下操作:

i < n-1