我需要在 SwiftUI(2.0,iOS 14)中创建一个可以平移和缩放的交互式“时间轴”视图。想想媒体播放器的进度视图,但它是交互式的。音频需要某种形状(我只是选择了 RoundedRectangle 作为下面的示例)并且“当前”时间需要表示为屏幕中间的垂直(黄色)线。
因为我需要能够设置和获取偏移量,所以我无法使用水平滚动视图。相反,我只是想根据缩放级别更改形状的帧大小。然后将“当前”时间线绘制为叠加层。在缩放级别高达 0.5 时,一切正常。
但是,当我放大(即使 zoomLevel 的值小于 0.45)时,对齐会变得混乱。我尝试过 ZStack 和其他一些组合,但没有运气。我认为问题在于形状大小导致叠加的位置计算错误,但即使将 ZStack 对齐设置为 [.leading,.center] 我也无法对齐黄线和形状。
这是代码。我该怎么做才能确保在调整形状大小时,正确计算覆盖的黄线以及形状的偏移量,以便它们保持在屏幕中央?
let zoomLevel:CGFloat = 1 // This is the value being modified
var body: some View {
GeometryReader { geometry in
RoundedRectangle(cornerRadius: 5)
.offset(x: getOffset(with: geometry.size.width))
.frame(width: getWidth(with: geometry.size.width),height: 150)
.overlay(Rectangle()
.frame(width: 2,height: geometry.size.height/5)
.foregroundColor(.yellow)
)
.frame(maxWidth: .infinity)
}
}
}
功能是:
private func getOffset(with width: CGFloat)->CGFloat {
let currentWidth = getWidth(with: width)
let offset = currentWidth/2 + 0 // 0 would be replaced with pan offset later
if offset > currentWidth/2 {
return currentWidth/2
} else if offset < -currentWidth/2 {
return -currentWidth/2
}
return offset
}
private func getWidth(with width: CGFloat)->CGFloat {
return 0.45*width/zoomLevel
}