简体   繁体   中英

How to draw circle with semi line in middle with swift UI for a button background?

I want to draw a shape that is already drawn on Android side as:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:innerRadius="0dp"
        android:shape="ring"
        android:thicknessRatio="2"
        android:useLevel="false">


    <stroke
            android:width="2dp"
            android:color="@color/color_boader" />
</shape>

目标形状

I have set it as button background that has "Sign Up" written on it as in the following image:

在此处输入图片说明

I want to do the same in iOS with SwiftUI. I have tried following with ZStack:

ZStack(alignment: .trailing) {
                        Spacer()
                            .frame(width: 40, height: 2)
                            .background(Color.boader)
                        Text("Sign up")
                            .foregroundColor(.white)
                            .padding()
                            .padding()
                            .overlay(
                                Circle()
                                    .stroke(Color.boader, lineWidth: 2))
                            .offset(x: 20)
                    }

Is there any better way to achieve this?

You can make your own Shape using Path and then use this shape as background for other view:

struct ButtonWithSpecialRing: View {

    var body: some View {

        Button(action: {
            print("signed in")
        }) {

            Text("Sign up!")
                .background(CircleWithSemiLine()
                    .stroke()
                    .foregroundColor(.gray))
        }

    }

}

struct CircleWithSemiLine: Shape {

    func path(in rect: CGRect) -> Path {

        var path = Path()
        let radius = rect.size.width / 2

        path.addArc(center: CGPoint(x: radius, y: radius / 2), radius: radius, startAngle: .degrees(0), endAngle: .degrees(360), clockwise: false)

        path.addLine(to: CGPoint(x: radius , y: radius / 2)) // you may play with radius to fit text

        return path

    }

}

You can play with offset a little or with radius for better centering. I had achieved only this result for a short time, but you can go further:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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