swift - 如何在 SwiftUI 中绘制自定义形状?

标签 swift xcode swiftui

亲爱的 IOS 开发者,您好。你能帮助我如何绘制我所附设计的几何形状吗? enter image description here

最佳答案

您可以通过使用 Path 和 GeometryReader 来实现这一点:

struct ContentView : View {
    var body: some View {
        Text("Breakfast")
            .foregroundColor(.white)
            .font(.title)
            .padding(20)
            .background(RoundedCorners(color: .green, topLeft: 10, topRight: 5, bottomLeft: 0, bottomRight: 30))
    }
}
struct RoundedCorners: View {
    var color: Color
    var topLeft: CGFloat = 0.0
    var topRight: CGFloat = 0.0
    var bottomLeft: CGFloat = 0.0
    var bottomRight: CGFloat = 0.0

    var body: some View {
        GeometryReader { geometry in
            Path { path in

                let w = geometry.size.width
                let h = geometry.size.height

                let tr = min(min(self.topRight, h/2), w/2)
                let tl = min(min(self.topLeft, h/2), w/2)
                let bl = min(min(self.bottomLeft, h/2), w/2)
                let br = min(min(self.bottomRight, h/2), w/2)

                path.move(to: CGPoint(x: w / 2.0, y: 0))
                path.addLine(to: CGPoint(x: w - tr, y: 0))
                path.addArc(center: CGPoint(x: w - tr, y: tr), radius: tr, startAngle: Angle(degrees: -90), endAngle: Angle(degrees: 0), clockwise: false)
                path.addLine(to: CGPoint(x: w, y: h - br))
                path.addArc(center: CGPoint(x: w - br, y: h - br), radius: br, startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 90), clockwise: false)
                path.addLine(to: CGPoint(x: bl, y: h))
                path.addArc(center: CGPoint(x: bl, y: h - bl), radius: bl, startAngle: Angle(degrees: 90), endAngle: Angle(degrees: 180), clockwise: false)
                path.addLine(to: CGPoint(x: 0, y: tl))
                path.addArc(center: CGPoint(x: tl, y: tl), radius: tl, startAngle: Angle(degrees: 180), endAngle: Angle(degrees: 270), clockwise: false)
            }
            .fill(self.color)
        }
    }
}

结果:

enter image description here

您可以找到更多信息here .

关于swift - 如何在 SwiftUI 中绘制自定义形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65207604/

相关文章:

swift - 在 ForEach/ZStack (SwiftUI) 中将表达式分解为不同的子表达式

ios - 以编程方式调用表情符号键盘?

ios - UIImage imageNamed 返回 nil

ios - PKPaymentAuthorizationViewController(paymentRequest:requestObject)返回nil

ios - VStack中的SwiftUI不同的对齐文本

swiftui - 在 SwiftUI 的按钮中放置背景图像和文本/图标?

ios - 还原列表 SwiftUI 中的底部填充

swift - 如何检测 App delegate - OSX 中的重启事件?

ios - Swift JSON可解码\u0000

xcode - 当我尝试通过OpenCv访问网络摄像头时,Xcode引发隐私错误