SwiftUI中圆角的自定义设置

随笔6个月前发布 缪斯
70 0 0
  1. 方法

@inlinable public func clipShape<S>(_ shape: S, style: FillStyle = FillStyle()) -> some View where S : Shape

  1. 样例

public struct CornerRectangle: Shape {
    var cornerRadius: CGFloat = 10
    
    public func path(in rect: CGRect) -> Path {
        return Path({ path in
            path.move(to: CGPoint(x: 0, y: 0))
            path.addLine(to: CGPoint(x: rect.width - cornerRadius, y: 0))
            path.addCurve(to: CGPoint(x: rect.width, y: cornerRadius), control1: CGPoint(x: rect.width, y: 0), control2: CGPoint(x: rect.width, y: cornerRadius))
            path.addLine(to: CGPoint(x: rect.width, y: rect.height - cornerRadius))
            path.addCurve(to: CGPoint(x: rect.width - cornerRadius, y: rect.height), control1: CGPoint(x: rect.width, y: rect.height - cornerRadius), control2: CGPoint(x: rect.width, y: rect.height))
            path.addLine(to: CGPoint(x: cornerRadius * 2, y: rect.height))
            path.addCurve(to: CGPoint(x: 0, y: rect.height - cornerRadius * 2), control1: CGPoint(x: cornerRadius * 2, y: rect.height), control2: CGPoint(x: 0, y: rect.height))
        })
    }
}

#Preview {
    Group {
        HStack {
            Text("圆角")
                .padding(EdgeInsets(top: 20, leading: 20, bottom: 20, trailing: 20))
        }
        .background(Color.red)
        .clipShape(CornerRectangle())
        CornerRectangle()
            .fill(Color.yellow)
            .frame(width: 100, height: 100)
    }
}

  1. 例图

    SwiftUI中圆角的自定义设置

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...