我正在使用 SwiftUI
,并且我想使用 ForEach
循环来绘制同心圆,以调整使用 Slider
突出显示的圆。当我运行以下代码时,我得到一个红色的圆圈,而我应该让第二个圆圈为蓝色,因为 Stepper
是 2.0。如何根据 slider 的值更新 View 的颜色。我还没有费心添加 slider ,因为我想首先获得一个恒定的值。有谁知道如何将这些同心圆堆叠在一起,其中一个同心圆根据变量的值显示与其余同心圆不同的颜色?
import SwiftUI
struct CircleView: View {
@State var color = Color.red
@State var stepperSelector = 2.0
var body: some View {
ZStack {
ForEach((0...5), id: \.self) { x in
Path { path in
var center = (x: 187, y:240)
var radius = Double(185) - Double(x) * Double(185 / 7)
let factor = Double(Int(radius)) / 5
path.move(to: CGPoint(x: center.x + Int(radius), y: center.y))
for i in stride(from: 0, to: 361, by: 1){
let center = CGPoint(x: 187, y: 240)
let i = Double(i)
let radians = i * Double.pi / 180
let x = radius * cos(radians) + Double(center.x)
let y = radius * sin(radians) + Double(center.y)
path.addLine(to: CGPoint(x: x, y: y))
}
}
.fill(self.color)
.onAppear{
if Int(self.stepperSelector) == Int(x) {
self.color = Color.blue
} else {
self.color = Color.red
}
}
}
}
}
}
struct CircleView_Previews: PreviewProvider {
static var previews: some View {
CircleView()
}
}
最佳答案
.fill
将填充路径内部,这就是输出单一红色圆圈的原因。此外,您可以内联切换颜色,而无需使用单独的状态变量。
struct CircleView: View {
@State var stepperSelector = 2.0
var body: some View {
ZStack {
ForEach((0...5), id: \.self) { x in
Path { path in
let center = (x: 187, y: 240)
let radius = Double(185) - Double(x) * Double(185 / 7)
path.move(to: CGPoint(x: center.x + Int(radius), y: center.y))
for i in stride(from: 0, to: 361, by: 1){
let center = CGPoint(x: 187, y: 240)
let i = Double(i)
let radians = i * Double.pi / 180
let x = radius * cos(radians) + Double(center.x)
let y = radius * sin(radians) + Double(center.y)
path.addLine(to: CGPoint(x: x, y: y))
}
}
.stroke(Int(self.stepperSelector) == Int(x) ? Color.blue : Color.red)
}
}
}
}
关于swift - 使用 ForEach 循环在 Swift 中用不同颜色绘制同心圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61470237/