Skip to content

Instantly share code, notes, and snippets.

@prafullakumar
Created January 24, 2021 13:24
Show Gist options
  • Save prafullakumar/14127d3248e71a48f36f7447bb67f178 to your computer and use it in GitHub Desktop.
Save prafullakumar/14127d3248e71a48f36f7447bb67f178 to your computer and use it in GitHub Desktop.
import SwiftUI
//step 1 -- Create a shape view which can give shape
struct CornerRadiusShape: Shape {
var radius = CGFloat.infinity
var corners = UIRectCorner.allCorners
func path(in rect: CGRect) -> Path {
let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
return Path(path.cgPath)
}
}
//step 2 - embed shape in viewModifier to help use with ease
struct CornerRadiusStyle: ViewModifier {
var radius: CGFloat
var corners: UIRectCorner
func body(content: Content) -> some View {
content
.clipShape(CornerRadiusShape(radius: radius, corners: corners))
}
}
//step 3 - crate a polymorphic view with same name as swiftUI's cornerRadius
extension View {
func cornerRadius(radius: CGFloat, corners: UIRectCorner) -> some View {
ModifiedContent(content: self, modifier: CornerRadiusStyle(radius: radius, corners: corners))
}
}
//use any way you want
struct ContentView: View {
var body: some View {
VStack {
Rectangle()
.frame(width: 100, height: 100, alignment: .center)
.cornerRadius(radius: 20.0, corners: [.topLeft])
Rectangle()
.frame(width: 100, height: 100, alignment: .center)
.cornerRadius(radius: 20.0, corners: [.topLeft, .bottomLeft])
Rectangle()
.frame(width: 100, height: 100, alignment: .center)
.cornerRadius(radius: 20.0, corners: [.allCorners])
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
// CornerRadiusShape.init(radius: 10, corners: [.allCorners])
// .frame(width: 100, height: 100, alignment: .center)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment