实现一个扫描二维码的动画效果,然而SwiftUI中没有提供CABasicAnimation 动画方法,该如何实现这种效果?先弄清楚什么关键帧动画,简单的说就是指视图从起点至终点的状态变化,可以是形状、位置、透明度等等
本文提供了一种方法Timer + offset + animation+@State,来实现位移变化
struct HomePage: View {
@State var openScanQR = false
@State var scanResult:String = ""
@State var isAnimated = false
@State var timer = Timer.publish(every: 3, on: .main, in: .common).autoconnect()
var body: some View {
VStack{
}
.ignoresSafeArea(edges: .top)
.fullScreenCover(isPresented: $openScanQR, content: {
ScannerView(result: $scanResult)
.overlay(ZStack{
Color.black.opacity(0.5)
Image("scan_round")
.resizable()
.renderingMode(.template)
.aspectRatio(contentMode: .fill)
.foregroundColor(.blue)
.frame(height: UIScreen.main.bounds.width - 80)
.padding(.horizontal, 40)
Image("scan_line")
.resizable()
.renderingMode(.template)
.aspectRatio(contentMode: .fill)
.foregroundColor(.blue)
.frame(height: 2)
.padding(.horizontal, 40)
.offset(y: !isAnimated ? -(UIScreen.main.bounds.width - 80)/2: (UIScreen.main.bounds.width - 80)/2)
.animation(.easeOut(duration: 3), value: isAnimated)
})
.edgesIgnoringSafeArea(.all)
})
.onReceive(timer, perform: { _ in
withAnimation {
isAnimated.toggle()
}
})
.background(Color.background_color)
.edgesIgnoringSafeArea(.top)
}
}