【发布时间】:2021-10-07 00:47:46
【问题描述】:
我需要在 SwiftUI(2.0,iOS 14)中创建一个可以平移和缩放的交互式“时间线”视图。想想媒体播放器的进度视图,但它是交互式的。音频需要是某种形状(我只是选择了 RoundedRectangle 作为下面的示例),并且“当前”时间需要表示为屏幕中间的垂直(黄色)线。
由于我需要能够设置和获取偏移量,我无法使用水平 ScrollView。相反,我只是想根据缩放级别更改形状的框架大小。然后将“当前”时间线绘制为覆盖。在高达 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
}
【问题讨论】:
-
我不完全确定您要达到的目标,但根据之前的经验,我知道 GeometryReader 会将内容与 .topLeading 对齐。我怀疑您想将内容与 .topCenter 对齐。最简单的方法是将 .frame(maxWidth: .infinity) 更改为 .frame(width: geometry.size.width)。
-
@Baglan 解决了这个问题!你想发表你的评论作为答案,以便我接受吗?
-
没关系,乐于助人! :)