Swift(macOS):如何将画线代码修改为绘制圆形?
Hey there! Let's work through adjusting your existing macOS line-drawing code to render circles instead—it's simpler than you might think. I'll walk through common AppKit-based drawing scenarios (the standard for macOS app graphics) with concrete examples.
First, a Quick Recap of Typical Line-Drawing Code
Chances are your line-drawing code looks something like this, implemented in a custom NSView subclass:
override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Draw a straight line let linePath = NSBezierPath() linePath.move(to: NSPoint(x: 50, y: 50)) linePath.line(to: NSPoint(x: 200, y: 200)) NSColor.blue.setStroke() linePath.lineWidth = 2 linePath.stroke() }
Option 1: Draw a Circle with oval(in:) (Quick & Easy)
The simplest way to draw a circle is using NSBezierPath(ovalIn:). Pass a square NSRect (equal width and height) to get a perfect circle:
override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Define square bounds for the circle let circleBounds = NSRect(x: 50, y: 50, width: 150, height: 150) let circlePath = NSBezierPath(ovalIn: circleBounds) // Configure stroke (outline) NSColor.red.setStroke() circlePath.lineWidth = 2 circlePath.stroke() // Optional: Add semi-transparent fill // NSColor.green.withAlphaComponent(0.5).setFill() // circlePath.fill() }
Option 2: Draw a Circle with addArc() (Precise Control)
If you need to specify the exact center and radius (instead of bounds), use the addArc(withCenter:radius:startAngle:endAngle:clockwise:) method. For a full circle, set the start angle to 0 and end angle to 360:
override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Define circle parameters let centerPoint = NSPoint(x: 125, y: 125) let circleRadius: CGFloat = 75 let circlePath = NSBezierPath() // Draw a full 360-degree arc (circle) circlePath.addArc(withCenter: centerPoint, radius: circleRadius, startAngle: 0, endAngle: 360, clockwise: true) // Style and render NSColor.orange.setStroke() circlePath.lineWidth = 2 circlePath.stroke() // Optional: Add soft fill // NSColor.yellow.withAlphaComponent(0.3).setFill() // circlePath.fill() }
Key Differences from Line Drawing
- Instead of using
move(to:)andline(to:), we leverage NSBezierPath's circle-specific methods ovalIn:creates an ellipse (or circle) based on rectangular bounds—keep width/height equal for a perfect circleaddArcgives you direct control over the circle's center point and radius, great for precise placements- Always set your desired stroke/fill color before calling
stroke()orfill()to render the shape
内容的提问来源于stack exchange,提问作者Devid Otladka

