SwiftUI:如何绘制填充和描边形状?

标签 swift swiftui

在 UIKit 中绘制描边和填充路径/形状非常容易。

例如,下面的代码绘制了一个带有蓝色描边的红色圆圈。

override func draw(_ rect: CGRect) {
    guard let ctx = UIGraphicsGetCurrentContext() else { return }
        
    let center = CGPoint(x: rect.midX, y: rect.midY)

    ctx.setFillColor(UIColor.red.cgColor)
    ctx.setStrokeColor(UIColor.blue.cgColor)
        
    let arc = UIBezierPath(arcCenter: center, radius: rect.width/2, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true)
        
    arc.stroke()
    arc.fill()
}

如何使用 SwiftUI 做到这一点?

Swift UI 似乎支持:

Circle().stroke(Color.blue)
// and/or
Circle().fill(Color.red)

但不是

Circle().fill(Color.red).stroke(Color.blue) // Value of type 'ShapeView<StrokedShape<Circle>, Color>' has no member 'fill'
// or 
Circle().stroke(Color.blue).fill(Color.red) // Value of type 'ShapeView<Circle, Color>' has no member 'stroke'

我应该只 ZStack 两个圆圈吗?这似乎有点傻。

最佳答案

你也可以结合使用strokeBorderbackground

代码:

Circle()
    .strokeBorder(Color.blue,lineWidth: 4)
    .background(Circle().foregroundColor(Color.red))

结果:

关于SwiftUI:如何绘制填充和描边形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56786163/

相关文章:

ios - 将数据从 UITableViewCell cocoa touch 类传输到 UIViewController 类

ios - MKAnnotation View 转场

ios - 初次启动后如何请求用户允许发送本地通知?

scrollview - UIPageViewController 中的 SwiftUI rollViewDidScroll 无法正常工作

ios - 从 SceneDelegate 更新屏幕结构的状态

button - SwiftUI:如何从 View 模型更新按钮状态

swift - 如何在一行中初始化某种类型的多个变量

swift - 处理 UrlSession 任务中的 NotConnectedToInternet 错误

swift - 如何将 SwiftUI 框架中 DatePicker 的外观更改为仅月份和年份?

swift - CAShapelayer 副本