如何在Xcode Playground中使用Swift绘制圆形(校园项目需求)
嘿,刚好我对Swift在Xcode里画圆形这块熟得很,不管你是在常规校园项目里做,还是想在Playground里快速测试,都给你一步步讲明白!
在Xcode常规iOS项目中绘制圆形
这里有两种常用的实现方式,你可以根据需求选:
方式1:用cornerRadius快速创建圆形视图
这种方式适合做纯色的圆形按钮、头像这类简单的圆形元素,代码超简洁:
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 1. 创建一个正方形视图(宽高必须相等才能变成正圆) let circleView = UIView(frame: CGRect(x: 100, y: 200, width: 150, height: 150)) // 2. 设置背景色 circleView.backgroundColor = .systemBlue // 3. 设置圆角为宽高的一半,这是关键! circleView.layer.cornerRadius = circleView.bounds.width / 2 // 4. 开启裁剪,确保视图内容不会超出圆角范围 circleView.clipsToBounds = true // 5. 添加到当前视图上 view.addSubview(circleView) } }
方式2:自定义UIView绘制圆形路径
如果需要给圆形加描边、渐变填充或者更复杂的绘制逻辑,就用这种自定义绘制的方式:
import UIKit // 自定义一个专门画圆形的View class CircleDrawView: UIView { override func draw(_ rect: CGRect) { super.draw(rect) // 1. 创建圆形路径,insetBy是给描边留空间,避免被裁剪 let circlePath = UIBezierPath(ovalIn: rect.insetBy(dx: 5, dy: 5)) // 2. 设置填充色并填充 UIColor.systemGreen.setFill() circlePath.fill() // 3. 设置描边颜色和宽度,然后描边 UIColor.black.setStroke() circlePath.lineWidth = 2 circlePath.stroke() } } // 在ViewController里使用这个自定义View class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let customCircle = CircleDrawView(frame: CGRect(x: 100, y: 400, width: 150, height: 150)) view.addSubview(customCircle) } }
在Xcode Playground中实现圆形绘制
Playground适合快速测试代码效果,步骤也很简单:
- 打开Xcode,选择「File」→「New」→「Playground」,选择「iOS」平台,命名后创建。
- 替换默认代码为下面的内容,就能实时看到圆形效果了:
import UIKit import PlaygroundSupport // 先创建一个容器视图,用来放我们的圆形 let container = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 500)) container.backgroundColor = .white // 方式1:用cornerRadius做纯色圆形 let simpleCircle = UIView(frame: CGRect(x: 75, y: 100, width: 150, height: 150)) simpleCircle.backgroundColor = .systemPink simpleCircle.layer.cornerRadius = simpleCircle.bounds.width / 2 simpleCircle.clipsToBounds = true container.addSubview(simpleCircle) // 方式2:自定义绘制带描边的圆形 class StrokedCircleView: UIView { override func draw(_ rect: CGRect) { let path = UIBezierPath(ovalIn: rect.insetBy(dx: 10, dy: 10)) UIColor.purple.setFill() path.fill() UIColor.white.setStroke() path.lineWidth = 3 path.stroke() } } let strokedCircle = StrokedCircleView(frame: CGRect(x: 75, y: 300, width: 150, height: 150)) container.addSubview(strokedCircle) // 告诉Playground显示我们的容器视图 PlaygroundPage.current.liveView = container
写完代码后,点击Playground右上角的「Run」按钮,就能在右侧面板看到两个圆形的实时预览啦~
内容的提问来源于stack exchange,提问作者Theresa White
相关产品推荐
相关产品推荐

