buttonswiftuiuibuttonstrokecornerradius

Button Stroke Set Gap In specific position Swiftui


I have added the borders for all sides using code below in SwiftUI. I want to trim stroke a particular position like below.

Want to achieve:-

Screen Shot

Output:-

ScreenShot

Code:-

import SwiftUI

struct RoundTrimImage: View {

var body: some View {
    VStack{
        Button(action: {
            print("Round Action")
        }) {
            Text("Press")
                .frame(width: 100, height: 100)
                .foregroundColor(Color.black)
                .background(Color.red)
                .clipShape(Circle()).padding(5)
                .overlay(
                    RoundedRectangle(cornerRadius: 100)
                        .trim(from: 0, to: CGFloat(0.8))
                        .stroke(Color.blue, lineWidth: 2)
                )
           }
         }
      }
  }

Question: Can someone please explain to me how to trim stoke particular position, I've tried with above code but no results yet.

Can someone please explain to me How to get Progress?

Any help would be greatly appreciated.

Thanks in advance.


Solution

  • The possible approach is to prepare needed shape using Arc and then rotate it to what ever position needed.

    Demo prepared with Xcode 13.2 / iOS 15.2

    demo

    struct DemoView: View {
    
        var body: some View {
            VStack{
                Button(action: {
                    print("Round Action")
                }) {
                    Text("Press")
                        .frame(width: 100, height: 100)
                        .foregroundColor(Color.black)
                        .background(Color.red)
                        .clipShape(Circle()).padding(5)
                        .overlay(
                            RotatedShape(shape: CutShape(), angle: .degrees(-120))
                                .stroke(Color.blue, lineWidth: 2)
                        )
                }
            }
        }
    }
    
    private struct CutShape: Shape {
        func path(in rect: CGRect) -> Path {
            Path {
                $0.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: rect.midY, startAngle: Angle(degrees: -5), endAngle: Angle(degrees: 5), clockwise: true)
            }
        }
    }