如何使半圆的边框适应其尺寸

mnemlml8  于 2022-10-04  发布在  Swift
关注(0)|答案(2)|浏览(188)

我正在制作一款需要使用半圆的应用程序。但我不能使它的边框与物体的真实大小相匹配。现在我正在修剪圆圈,但我真的不知道你是否真的裁剪了视图。

下面是我如何修剪圆圈的方法:

  1. Circle()
  2. .trim(from: 0, to: 0.5)
  3. .fill(Color.blue)
  4. .background(Color.red)

我的背景是红色,比我的新物体大了两倍。

t0ybt7op

t0ybt7op1#

最好是自己制作符合ShapeHalfCircle,而不是试图将Circle拼凑成您需要的形状。让我们更进一步,使其符合InsettableShape,以防您想要使用它来描边。

  1. import SwiftUI
  2. struct HalfCircle: InsettableShape {
  3. var _inset: CGFloat = 0
  4. func inset(by amount: CGFloat) -> Self {
  5. var copy = self
  6. copy._inset += amount
  7. return copy
  8. }
  9. func path(in rect: CGRect) -> Path {
  10. var path = Path()
  11. // This is a half-circle centered at the origin with radius 1.
  12. path.addArc(
  13. center: .zero,
  14. radius: 1,
  15. startAngle: .zero,
  16. endAngle: .radians(.pi),
  17. clockwise: false
  18. )
  19. path.closeSubpath()
  20. // Since it's the bottom half of a circle, we only want
  21. // to inset the left, right, and bottom edges of rect.
  22. let rect = rect
  23. .insetBy(dx: _inset, dy: 0.5 * _inset)
  24. .offsetBy(dx: 0, dy: -(0.5 * _inset))
  25. // This transforms bounding box of the path to fill rect.
  26. let transform = CGAffineTransform.identity
  27. .translatedBy(x: rect.origin.x + 0.5 * rect.size.width, y: 0)
  28. .scaledBy(x: rect.width / 2, y: rect.height)
  29. return path.applying(transform)
  30. }
  31. }

我们可以用它来画这个:

使用这个Playground:

  1. import PlaygroundSupport
  2. PlaygroundPage.current.setLiveView(HalfCircle()
  3. .inset(by: 20)
  4. .fill(.black)
  5. .background(.gray)
  6. .aspectRatio(2, contentMode: .fit)
  7. .frame(width: 200)
  8. .padding()
  9. )
展开查看全部
gpnt7bae

gpnt7bae2#

您可以使用GeometryReader以不同方式对其进行掩码:

  1. GeometryReader { proxy in
  2. Circle()
  3. .fill(.blue)
  4. .offset(y: -proxy.size.height) // <- Shows bottom part
  5. .frame(height: proxy.size.width) // <- Makes the circle match frame
  6. .background(.red) // <- Just for testing
  7. }
  8. .aspectRatio(2, contentMode: .fit) // <- Makes the frame ration 2 : 1 (landscape rectangle)
  9. .clipped() // <- Removes out of bound drawings

相关问题