✨RoundedCorners
自製的 Shape,可以自由設定四個角落的圓角半徑,四個半徑可以各自不同。
Last updated
自製的 Shape,可以自由設定四個角落的圓角半徑,四個半徑可以各自不同。
Last updated
import SwiftUI
// ⭐️ required: 🅿️Vector2D, 🌀CGRect
public struct RoundedCorners: Shape {
// corner radii
let topLeft : CGFloat
let topRight : CGFloat
let bottomRight: CGFloat
let bottomLeft : CGFloat
// init
public init(
topLeft r1: CGFloat = 0,
topRight r2: CGFloat = 0,
bottomRight r3: CGFloat = 0,
bottomLeft r4: CGFloat = 0
) {
self.topLeft = r1
self.topRight = r2
self.bottomRight = r3
self.bottomLeft = r4
}
public func path(in rect: CGRect) -> Path {
// related dimensions
let w = rect.width
let h = rect.height
let m = rect.minLength / 2 // max radius allowed
// calculate radii
let r1 = min(topLeft, m)
let r2 = min(topRight, m)
let r3 = min(bottomRight, m)
let r4 = min(bottomLeft, m)
// draw path
return Path { path in
// starting point: top center
path.move(to: [w/2, 0])
// to top right
path.addLine(to: [w - r2, 0])
path.addArc(
center : [w - r2, r2],
radius : r2,
startAngle: .degrees(-90),
endAngle : .degrees(0),
clockwise : false
)
// to bottom right
path.addLine(to: [w, h - r3])
path.addArc(
center : [w - r3, h - r3],
radius : r3,
startAngle: .degrees(0),
endAngle : .degrees(90),
clockwise : false
)
// to bottom left
path.addLine(to: [r4, h])
path.addArc(
center : [r4, h - r4],
radius : r4,
startAngle: .degrees(90),
endAngle : .degrees(180),
clockwise : false
)
// to top left
path.addLine(to: [0, r1])
path.addArc(
center : [r1, r1],
radius : r1,
startAngle: .degrees(180),
endAngle : .degrees(270),
clockwise : false
)
// close path
path.closeSubpath()
}
}
}
struct ContentView: View {
let shape = RoundedCorners( // ⭐️ RoundedCorners
topLeft: 40, topRight: 40,
bottomRight: 80, bottomLeft: 80
)
var body: some View {
ZStack {
shape
.fill(Color.pink)
.overlay(shape.stroke(Color.purple, lineWidth: 20))
shape.stroke()
} // ZStack (container)
.padding(40)
.shadow( radius: 16)
.frame(width: 300, height: 300)
.background(Color.gray)
}
}