简体   繁体   English

自定义圆角矩形形状

[英]Custom RoundedRectangle Shape

I am working on a project with a custom roundedRectangle Shape that have a bump in one of its side, and from what i researched i have to draw a shape using custom path... however i wan't very successful in doing so, and i don't understand how to create it.我正在开发一个带有自定义 roundedRectangle Shape 的项目,它的一侧有一个凸起,根据我的研究,我必须使用自定义路径绘制一个形状......但是我这样做并不是很成功,并且我不明白如何创建它。

I would be grateful if someone help me create the shape in this attachment:如果有人帮助我创建此附件中的形状,我将不胜感激: 带有凹凸的自定义 RoundedRectangle

To draw custom shapes with rounded corners, .addArc is your friend.要绘制带有圆角的自定义形状, .addArc是你的朋友。

struct LabelShape: Shape {
    let cornerRadius: CGFloat
    let tabWidth: CGFloat
        
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.move(to: CGPoint(x: cornerRadius, y: rect.height))
        path.addArc(tangent1End: CGPoint(x: rect.width, y: rect.height), tangent2End: CGPoint(x: rect.width, y: 0), radius: cornerRadius)
        path.addArc(tangent1End: CGPoint(x: rect.width, y: 0), tangent2End: CGPoint(x: 0, y: 0), radius: cornerRadius)
        path.addArc(tangent1End: CGPoint(x: rect.width - tabWidth, y: 0), tangent2End: CGPoint(x: rect.width - tabWidth, y: rect.height), radius: cornerRadius)
        path.addArc(tangent1End: CGPoint(x: rect.width - 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: rect.height), radius: cornerRadius)
        path.addArc(tangent1End: CGPoint(x: 0, y: rect.height), tangent2End: CGPoint(x: rect.width, y: rect.height), radius: cornerRadius)
        return path
    }
}

which you can use like this:你可以这样使用:

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)
        }
    }
}

在此处输入图像描述

For a great explanation on how this version of addArc works, see https://stackoverflow.com/a/71683201/123632有关此版本的addArc工作原理的详细解释,请参阅https://stackoverflow.com/a/71683201/123632

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM