获取溢出对象的边界以缩小到父视图

问题描述 投票:0回答:1

我正在制作单位圆的表示,并将点标签排列在一个圆圈中。 我知道标签的原点位于中心,因此它们溢出了父级。

解决此问题的最佳方法是什么? 有没有办法抓住溢出的边界并调整它们的大小以适合组内部,或者有不同的解决方案?

struct UnitCircle: View {
  var body: some View {
    GeometryReader { geometry in
      let diameter = min(geometry.size.width, geometry.size.height)
      let radius = (diameter / 2)
      
      Group {
        ForEach(unitCirclePoints, id: \.angle) { point in
          VStack {
            PointView(point: point).border(.red).scaleEffect(0.3)
          }
          .position(
            x: radius * CGFloat(cos(Double(-point.angle) * .pi / 180)) + radius,
            y: radius * CGFloat(sin(Double(-point.angle) * .pi / 180)) + radius
          )
        }
      }.border(.red)
      
        .frame(width: diameter, height: diameter)
        .position(x: geometry.size.width / 2, y: geometry.size.height / 2)
    }
  }
}

Unit circle with labels arranged in a circle, the labels overflow the parent bounds.

swift swiftui
1个回答
0
投票

把半径调小一点就可以了。

例如,这里我将半径减小了30pt。

let diameter = min(geometry.size.width, geometry.size.height)
let radius = (diameter / 2) - 30 // here

Group {
    ForEach(stride(from: 0, to: 360, by: 45).map { Double($0) }, id: \.self) { point in
        // as an example, I will be drawing 8 smaller circles, instead of the coordinates
        Circle()
            .frame(width: 30)
            .position(
                // here you need to add back the 30pt so that the circle is centered
                x: radius * CGFloat(cos(-point * .pi / 180)) + radius + 30,
                y: radius * CGFloat(sin(-point * .pi / 180)) + radius + 30
            )
    }
}
.border(.red)
.frame(width: diameter, height: diameter)
.position(x: geometry.size.width / 2, y: geometry.size.height / 2)
© www.soinside.com 2019 - 2024. All rights reserved.