SwiftUI 使用贝塞尔曲线绘制圆角

项目中经常使用到圆角或者菱角之类的,最快捷简单的方法就直接找UI切图,少则好说,多则占存储空间。直接用系统自带的绘制圆角的方法,又怕出现离屏渲染,这个时候就考虑使用贝塞尔曲线绘制圆角或者菱角。
以下是绘制圆角的写法(菱角同理)

struct LynnFilletPolygon: Shape {
    let a: CGFloat
    let b: CGFloat
    
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.move(to: CGPoint(x: 0, y: b))
        path.addQuadCurve(
            to: CGPoint(x: a, y: 0),
            control: CGPoint(x: 0, y: 0)
        )
        path.addLine(to: CGPoint(x: rect.width-a, y: 0))
        path.addQuadCurve(
            to: CGPoint(x: rect.width, y: b),
            control: CGPoint(x: rect.width, y: 0)
        )
        
        path.addLine(to: CGPoint(x: rect.width, y: rect.height-b))
        path.addQuadCurve(
            to: CGPoint(x: rect.width-a, y: rect.height),
            control: CGPoint(x: rect.width, y: rect.height)
        )
        path.addLine(to: CGPoint(x: a, y: rect.height))
        path.addQuadCurve(
            to: CGPoint(x: 0, y: rect.height-b),
            control: CGPoint(x: 0, y: rect.height)
        )
        path.addLine(to: CGPoint(x: 0, y: b))
        
        return path
    }
}

你可能感兴趣的:(SwiftUI 使用贝塞尔曲线绘制圆角)