自定义圆角矩形形状

问题描述 投票:0回答:1

我正在开发一个具有自定义圆角矩形形状的项目,该形状的一侧有一个凹凸,根据我的研究,我必须使用自定义路径绘制一个形状... 但是我这样做不太成功,而且我不明白如何创建它。

如果有人帮助我创建此附件中的形状,我将不胜感激: Custom RoundedRectangle with a bump

swiftui shapes
1个回答
3
投票

要绘制带圆角的自定义形状,

.addArc
是您的朋友。

struct LabelShape: Shape {
    let cornerRadius: CGFloat
    let tabWidth: CGFloat
        
    func path(in rect: CGRect) -> Path {
        var path = Path()
        
        let w = rect.width
        let h = rect.height
        
        path.move(to: CGPoint(x: cornerRadius, y: rect.height))
        
        path.addArc(tangent1End: CGPoint(x: w, y: h), tangent2End: CGPoint(x: w, y: 0), radius: cornerRadius)
        path.addArc(tangent1End: CGPoint(x: w, y: 0), tangent2End: CGPoint(x: 0, y: 0), radius: cornerRadius)
        path.addArc(tangent1End: CGPoint(x: w - tabWidth, y: 0), tangent2End: CGPoint(x: w - tabWidth, y: h), radius: cornerRadius)
        path.addArc(tangent1End: CGPoint(x: w - tabWidth, y: cornerRadius * 2), tangent2End: CGPoint(x: 0, y: cornerRadius * 2), radius: cornerRadius)
        path.addArc(tangent1End: CGPoint(x: 0, y: cornerRadius * 2), tangent2End: CGPoint(x: 0, y: h), radius: cornerRadius)
        path.addArc(tangent1End: CGPoint(x: 0, y: rect.height), tangent2End: CGPoint(x: w, y: h), radius: cornerRadius)
        
        return path
    }
}

你可以这样使用:

struct ContentView: View {
    
    var body: some View {
        ZStack(alignment: .topTrailing) {
            LabelShape(cornerRadius: 10, tabWidth: 110)
                .stroke(.red)
                .frame(width: 300, height: 100)
            HStack(alignment: .firstTextBaseline, spacing: 4) {
                Text("01:59:43")
                    .font(.system(size: 14, weight: .bold))
                Text("Hours")
                    .font(.system(size: 10, weight: .regular))
            }
            .padding(4)
        }
    }
}

enter image description here

有关此版本

addArc
如何工作的详细说明,请参阅 https://stackoverflow.com/a/71683201/123632

© www.soinside.com 2019 - 2024. All rights reserved.