【问题标题】:Need to clipShape with a Shape that has only top left and bottom left rounded corners需要使用只有左上角和左下角圆角的形状来剪辑形状
【发布时间】:2021-05-25 23:27:55
【问题描述】:

我想将clipShape 修饰符应用于只有左上角和左下角圆角的圆角矩形。

我正在使用this extension 对我拥有的某些视图的特定角进行圆角处理。

所以,如果我能做到这一点,我会很高兴:

.clipShape(Rectangle().cornerRadius(20, [.topLeft, .topRight]))

但我收到错误说 Rectangle must be a shape...

所以我想我必须创建类似的东西:

struct RectangleX: Shape { 
  func path(in rect: CGRect) -> Path {
    var radius = CGFloat.infinity
    var corners = UIRectCorner.allCorners
    let path = UIBezierPath(roundedRect: rect,
                            byRoundingCorners: corners,
                            cornerRadii: CGSize(width: radius,
                                                height: radius))
    return Path(path.cgPath)
  }
}

但我看不到如何将矩形传递给它。

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    问题

    cornerRadius 修饰符已使用clipShape

    extension View {
        func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
            clipShape( RoundedCorner(radius: radius, corners: corners) )
        }
    }
    

    这意味着:

    .clipShape(Rectangle().cornerRadius(20, [.topLeft, .topRight]))
    

    也可以读作:

    .clipShape(Rectangle().clipShape( RoundedCorner(radius: 20, corners: [.topLeft, .topRight]) ))
    

    而且您实际上并不需要多个 clipShape 修饰符。

    解决方案

    改用以下方法(您不需要使用 clipShape - 自定义 cornerRadius 扩展程序已经调用它):

    .cornerRadius(20, corners: [.topLeft, .topRight])
    

    一个更完整的例子:

    struct ContentView: View {
        var body: some View {
            Rectangle()
                .fill(Color.red)
                .frame(width: 100, height: 100)
                .cornerRadius(20, corners: [.topLeft, .topRight])
        }
    }
    

    或者,您可以明确使用clipShape

    .clipShape(RoundedCorner(radius: 20, corners: [.topLeft, .topRight]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-12
      • 2021-01-29
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      • 2021-01-13
      • 2018-02-03
      相关资源
      最近更新 更多