ios 在SwiftUI中围绕圆圈旋转图像,使图像在屏幕上保持直立

agyaoht7  于 11个月前  发布在  iOS
关注(0)|答案(1)|浏览(115)

我有3张图片,它们都在一个圆圈中的不同位置。我想让这些图片在绕圆圈的整个过程中,在屏幕上保持直立的同时,以顺时针方向绕圆圈旋转。在下面的代码中,它们是以顺时针方向移动的。但是当它们相对于屏幕在圆周上移动时并不保持直立。它们相对于屏幕的中心在圆周上保持直立。那个圆圈。
有人知道如何确保图像相对于屏幕保持垂直吗?另外,如果有人建议尝试逆时针旋转,请尝试在旋转Angular 变量中添加一个“-"号,您会看到它只是逆时针旋转。
谢谢,下面是我的代码:

import SwiftUI

struct AnotherCircleTry: View {
    @State private var rotationAngle = 0.0

    var body: some View {
        VStack {
            Spacer()
            Text("Rotating images!")
            Spacer()

            ZStack {
                Circle()
                    .stroke()
                    .frame(width: 250, height: 250)
                    .hidden()

                // Image 1
                Image("image-1")
                    .resizable()
                    .frame(width: 50, height: 50)
                    .clipShape(Circle())
                    .offset(x: cos(CGFloat(rotationAngle) / 180.0 * .pi) * 100,
                            y: sin(CGFloat(rotationAngle) / 180.0 * .pi) * 100)
                    .rotationEffect(.degrees(rotationAngle), anchor: .center)

                // Image 2
                Image("image-2")
                    .resizable()
                    .frame(width: 50, height: 50)
                    .clipShape(Circle())
                    .offset(x: cos(CGFloat(rotationAngle) / 180.0 * .pi) * 100,
                            y: sin(CGFloat(rotationAngle) / 180.0 * .pi) * 100)
                    .rotationEffect(.degrees((rotationAngle + 120)), anchor: .center)

                // Image 3
                Image("image-3")
                    .resizable()
                    .frame(width: 50, height: 50)
                    .clipShape(Circle())
                    .offset(x: cos(CGFloat(rotationAngle) / 180.0 * .pi) * 100,
                            y: sin(CGFloat(rotationAngle) / 180.0 * .pi) * 100)
                    .rotationEffect(.degrees((rotationAngle + 240)), anchor: .center)
            }
            .padding(.horizontal)
            
            Spacer()
        }
        .onAppear {
            withAnimation(Animation.linear(duration: 8).repeatForever(autoreverses: false)) {
                rotationAngle += 360
            }
        }
    }
}

#Preview{
        AnotherCircleTry()
}

字符串

r7s23pms

r7s23pms1#

您需要在offset修改器之前应用相反的旋转:

Image("image-1")
    .resizable()
    .frame(width: 50, height: 50)
    .clipShape(Circle())
    .rotationEffect(.degrees(-rotationAngle), anchor: .center) // <- NEW
    .offset(
        x: cos(CGFloat(rotationAngle) / 180.0 * .pi) * 100,
        y: sin(CGFloat(rotationAngle) / 180.0 * .pi) * 100
    )
    .rotationEffect(.degrees(rotationAngle), anchor: .center)

字符串

相关问题