Created
October 13, 2022 17:54
-
-
Save MaxenceMottard/a02d807b0c7b49065bd033713921e9c3 to your computer and use it in GitHub Desktop.
Ticket Shape SwiftUI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct TicketShape: Shape { | |
let cornerRadius: CGFloat | |
let center: CGFloat | |
let radius: CGFloat? | |
fileprivate init(cornerRadius: CGFloat, center: CGFloat, radius: CGFloat? = nil) { | |
self.cornerRadius = cornerRadius | |
self.center = center | |
self.radius = radius | |
} | |
func path(in rect: CGRect) -> Path { | |
Path { path in | |
let width: CGFloat = rect.width | |
let height: CGFloat = rect.height | |
let radius: CGFloat = self.radius ?? 0.12 * height | |
// Top Right Angle | |
path.addArc( | |
center: .init(x: width - cornerRadius, y: cornerRadius), | |
radius: cornerRadius, | |
startAngle: .degrees(-90), | |
endAngle: .degrees(0), | |
clockwise: false | |
) | |
// Right Arc | |
path.addArc( | |
center: .init(x: width, y: center * height), | |
radius: radius, | |
startAngle: .degrees(-90), | |
endAngle: .degrees(-270), | |
clockwise: true | |
) | |
// Bottom Right Corner | |
path.addArc( | |
center: .init(x: width - cornerRadius, y: height - cornerRadius), | |
radius: cornerRadius, | |
startAngle: .degrees(0), | |
endAngle: .degrees(90), | |
clockwise: false | |
) | |
// Bottom Left Corner | |
path.addArc( | |
center: .init(x: cornerRadius, y: height - cornerRadius), | |
radius: cornerRadius, | |
startAngle: .degrees(90), | |
endAngle: .degrees(180), | |
clockwise: false | |
) | |
// Left Arc | |
path.addArc( | |
center: .init(x: 0, y: center * height), | |
radius: radius, | |
startAngle: .degrees(90), | |
endAngle: .degrees(270), | |
clockwise: true | |
) | |
// Top Left Corner | |
path.addArc( | |
center: .init(x: cornerRadius, y: cornerRadius), | |
radius: cornerRadius, | |
startAngle: .degrees(180), | |
endAngle: .degrees(270), | |
clockwise: false | |
) | |
path.closeSubpath() | |
} | |
} | |
} | |
extension Shape where Self == TicketShape { | |
static func ticket( | |
cornerRadius: CGFloat = 0, | |
center: CGFloat = 0.5, | |
radius: CGFloat? = nil | |
) -> TicketShape { | |
TicketShape(cornerRadius: cornerRadius, center: center, radius: radius) | |
} | |
} | |
struct VerticalTicketShape_Previews: PreviewProvider { | |
static var previews: some View { | |
VStack { | |
Color.red | |
.frame(width: 200, height: 200) | |
.clipShape(.ticket(center: 0.3)) | |
Color.blue | |
.frame(width: 300, height: 200) | |
.clipShape(.ticket(cornerRadius: 25, radius: 40)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment