gpt4 book ai didi

swift - 如何在 SWIFTUI 中进行修剪旋转?

转载 作者:行者123 更新时间:2023-12-02 15:45:54 29 4
gpt4 key购买 nike

我有一个 RoundedRectangle,我想让修剪永远旋转并从中制作一个漂亮的动画。 I added you this image here, so you can see what kind of trim I am talking about

尝试做了一个旋转效果和3d旋转效果,但是没有效果

@State private var show = false

var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 20, style: .continuous)
.foregroundColor(.gray.opacity(0.1))
.frame(width: 195, height: 50)


RoundedRectangle(cornerRadius: 20, style: .continuous)
.trim(from: 0.25, to: 0.5)
.stroke(style: StrokeStyle(lineWidth: 3, lineCap: .round))
.frame(width: show ? 50 : 200, height: show ? 200 : 50)
.rotationEffect(Angle(degrees: show ? 90 : 0))
.animation(.linear.delay(1).repeatForever(autoreverses: true),
value: show)

RoundedRectangle(cornerRadius: 20, style: .continuous)
.trim(from: 0.75, to: 1)
.stroke(style: StrokeStyle(lineWidth: 3, lineCap: .round))
.frame(width: show ? 50 : 200, height: show ? 200 : 50)
.rotationEffect(Angle(degrees: show ? 90 : 0))
.animation(.linear.delay(1).repeatForever(autoreverses: true),
value: show)

Text("title")
.foregroundStyle(LinearGradient(gradient: Gradient(colors: colors),
startPoint: .topLeading,
endPoint: .bottomTrailing))
}
.onAppear {
show.toggle()
}

这是我的代码。让它移动,但不是想要的方式......可以更平滑,就像两条蛇一条接一条地移动

最佳答案

enter image description here


为修剪偏移量的变化设置动画。由于动画很难越过 01 的边界,请使用 .rotation(Angle(degrees: 180)) 始终保持在01 的边界:

struct ContentView: View {
let colors = [Color.green, Color.blue]
@State private var offset = 0.0

var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 20, style: .continuous)
.foregroundColor(.gray.opacity(0.1))
.frame(width: 195, height: 50)

RoundedRectangle(cornerRadius: 20, style: .continuous)
.trim(from: 0.25 + offset, to: 0.5 + offset)
.stroke(style: StrokeStyle(lineWidth: 3, lineCap: .round))
.frame(width: 195, height: 50)

RoundedRectangle(cornerRadius: 20, style: .continuous)
.trim(from: 0.25 + offset, to: 0.5 + offset)
.stroke(style: StrokeStyle(lineWidth: 3, lineCap: .round))
.rotation(Angle(degrees: 180))
.frame(width: 195, height: 50)

Text("title")
.foregroundStyle(LinearGradient(gradient: Gradient(colors: colors),
startPoint: .topLeading,
endPoint: .bottomTrailing))
}
.onAppear {
withAnimation(.linear(duration: 0.75).repeatForever(autoreverses: false)) {
offset = 0.5
}
}
}
}

优化代码

由于这两条“蛇”除了旋转 180º 外完全相同,我们可以使用 ForEach 对此进行编码:

ForEach([0.0, 180.0], id: \.self) { rotation in
RoundedRectangle(cornerRadius: 20, style: .continuous)
.trim(from: 0.25 + offset, to: 0.5 + offset)
.stroke(style: StrokeStyle(lineWidth: 3, lineCap: .round))
.rotation(Angle(degrees: rotation))
.frame(width: 195, height: 50)
}

关于swift - 如何在 SWIFTUI 中进行修剪旋转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74253730/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com