Skip to content

Instantly share code, notes, and snippets.

@bnulo
Last active January 15, 2024 22:24
Show Gist options
  • Save bnulo/713b288cf0f6bd3d940d8271736652c8 to your computer and use it in GitHub Desktop.
Save bnulo/713b288cf0f6bd3d940d8271736652c8 to your computer and use it in GitHub Desktop.
How to implement Capsule Shape in SwiftUI?
//
// CapsuleShape.swift
//
//
// Created by bnulo on 1/16/24.
//
import SwiftUI
// Preview on YouTube: https://bit.ly/3Sk6Dyv
struct CapsuleShape: Shape {
func path(in rect: CGRect) -> Path {
let min = (rect.width < rect.height) ? rect.width : rect.height
return Path { path in
path.addRoundedRect(in: CGRect(x: 0, y: 0,
width: rect.width,
height: rect.height),
cornerSize: CGSize(width: min/2.37, height: min/2.37),
style: .continuous)
}
}
}
struct CapsulePreview: View {
var body: some View {
VStack {
CapsuleShape()
.fill(Color.black)
.frame(maxWidth: .infinity)
.frame(height: 60)
CapsuleShape()
.fill(Color.indigo)
.frame(width: 120, height: 120)
CapsuleShape()
.fill(Color.mint)
.frame(maxWidth: .infinity,
maxHeight: .infinity)
}
.padding(.horizontal)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment