如何在SwiftUI中获取桥梁形状

c2e8gylq  于 2024-01-05  发布在  Swift
关注(0)|答案(2)|浏览(162)

我正在SwiftUI中通过组合矩形和圆形来创建一个“桥”形状。我相信使用.union这样的方法可能是解决方案,但我在弄清楚如何正确实现它方面遇到了麻烦。我的目标是合并矩形和圆形来创建一个类似于桥的形状。具体来说,我希望矩形的顶部有一个插入曲线。另外,我想在这个复合形状的背景中放置一个图像。基本上,最终的设计应该是一个矩形,顶部有一个弯曲的插图,后面有一个图像。
有帮助就太好了!谢谢!

  1. ZStack {
  2. Rectangle()
  3. .fill(.blue)
  4. .frame(height:250)
  5. Image("BGImage")
  6. Circle()
  7. .fill(.white)
  8. .frame(width: 700)
  9. .offset(y:-400)
  10. }

字符串
这就是目标:
x1c 0d1x的数据

z9ju0rcb

z9ju0rcb1#

  1. import SwiftUI
  2. struct BridgeShape: Shape {
  3. func path(in rect: CGRect) -> Path {
  4. let width = rect.width
  5. let height = rect.height
  6. let bridgeHeight: CGFloat = height * 0.7 // Adjust the height of the bridge
  7. let curveHeight: CGFloat = height * 0.1 // Adjust the height of the curved inset
  8. var path = Path()
  9. // Starting from the top-left corner
  10. path.move(to: CGPoint(x: 0, y: 0))
  11. // Top horizontal line
  12. path.addLine(to: CGPoint(x: width, y: 0))
  13. // Top right curve inset
  14. path.addQuadCurve(to: CGPoint(x: width, y: curveHeight), control: CGPoint(x: width * 0.8, y: curveHeight))
  15. // Top right corner of the bridge
  16. path.addLine(to: CGPoint(x: width, y: bridgeHeight))
  17. // Bottom right corner
  18. path.addLine(to: CGPoint(x: 0, y: bridgeHeight))
  19. // Closing the shape
  20. path.closeSubpath()
  21. return path
  22. }
  23. }
  24. struct ContentView: View {
  25. var body: some View {
  26. ZStack {
  27. Image("BGImage")
  28. .resizable()
  29. .scaledToFill()
  30. .edgesIgnoringSafeArea(.all)
  31. BridgeShape()
  32. .fill(Color.blue)
  33. .frame(height: 250)
  34. }
  35. }
  36. }
  37. struct ContentView_Previews: PreviewProvider {
  38. static var previews: some View {
  39. ContentView()
  40. }
  41. }

字符串
将“BGImage”替换为图像资源的名称。调整BridgeShape结构中的bridgeHeight和curveHeight的值,以根据需要修改桥的外观。

展开查看全部
ukxgm1gy

ukxgm1gy2#

当你说你想:
在此复合形状的背景中放置图像
你的意思是,图像应该在形状后面(换句话说,形状覆盖了图像的一部分),还是你想用图像填充形状?

  • 如果你想让图片在形状的后面,那么Shape可能是最好的方法,因为这样图片会透过形状的非填充区域显示出来。还有另一个答案可以说明如何做到这一点。
  • 然而,如果你想用图像填充形状,那么听起来就像我们只是在谈论从图像中“咬”一口。这可以通过覆盖来完成。

对于覆盖方法,您可能希望咬痕的大小取决于图像的宽度。可以使用GeometryReader来测量此大小。
就像这样:

  1. Image("BGImage")
  2. .resizable()
  3. .scaledToFill()
  4. .frame(height: 250)
  5. .overlay {
  6. GeometryReader { proxy in
  7. let w = proxy.size.width
  8. let factor = 1.8 // smaller factor = deeper bite
  9. let xOffsetFactor = (factor - 1) / 2
  10. let yOffsetFactor = (factor + sqrt((factor * factor) - 1)) / 2
  11. Circle()
  12. .fill(Color(UIColor.systemBackground))
  13. .frame(width: w * factor)
  14. .offset(x: -w * xOffsetFactor, y: -w * yOffsetFactor)
  15. .fixedSize()
  16. }
  17. }
  18. .clipped()

字符串

展开查看全部

相关问题