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

问题描述 投票:0回答:2

我发现这个代码用于绘制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)
}

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

swift macos cocoa draw geometry
2个回答
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()
    }
}

0
投票

根据圆圈的不同,您也可以这样做:

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)
}
© www.soinside.com 2019 - 2024. All rights reserved.