SwiftUI中rotationEffect动画为何出现垂直位移?
旋转动画时图片垂直移动的原因及解决方法
问题原因
你用Text(Image(systemName: "arrow.triangle.2.circlepath"))把系统图标包裹在Text组件里,Text是基于文字基线来布局的。当图标旋转时,Text容器的垂直对齐基准(基线)固定不变,但图标旋转过程中视觉重心和Text基线的相对位置发生了变化,就会出现垂直方向的晃动。
解决方法
最直接有效的方式是去掉Text包裹,直接使用Image组件,这样视图的旋转中心是自身几何中心,动画过程中不会受文字基线影响产生位移:
struct SyncView: View { @State var isSyncing = false let animation: Animation = Animation.linear(duration: 2.0).repeatForever(autoreverses: false) var body: some View { VStack(spacing: 16) { HStack { VStack(alignment: .leading) { Text("Linked Device's Name") Text("Updating (Last update: Oct 1, 2022)") .font(.callout) .foregroundColor(.gray) } Spacer() // 直接使用Image替代Text包裹系统图标 Image(systemName: "arrow.triangle.2.circlepath") .foregroundStyle(Color.yellow) .font(.title) .rotationEffect(Angle.degrees(isSyncing ? 360 : 0)) .animation(animation, value: isSyncing) } } .padding() .onAppear { isSyncing = true } } }
如果一定要用Text包裹(比如需要和其他文字混排),可以通过添加alignmentGuide强制修正垂直对齐:
Text(Image(systemName: "arrow.triangle.2.circlepath")) .foregroundStyle(Color.yellow) .font(.title) .alignmentGuide(.center) { d in d[.center] } // 强制按中心对齐 .rotationEffect(Angle.degrees(isSyncing ? 360 : 0)) .animation(animation, value: isSyncing)
不过前者的方案更简洁可靠,推荐优先使用。
内容的提问来源于stack exchange,提问作者Aaron Bratcher
相关产品推荐
相关产品推荐

