Custom shapes with Arcs and Quad Curves in SwiftUI | Advanced Learning #6
struct WaterShape: Shape {
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: rect.minX, y: rect.midY))
path.addQuadCurve(to: CGPoint(x: rect.midX, y: rect.midY),
control: CGPoint(x: rect.width * 0.25, y: rect.height * 0.40))
path.addQuadCurve(to: CGPoint(x: rect.maxX, y: rect.midY),
control: CGPoint(x: rect.width * 0.75, y: rect.height * 0.60))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
}
}
}
import SwiftUI
struct ShapeWithArc: Shape {
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: rect.minX, y: rect.minY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
path.addArc(center: CGPoint(x: rect.midX, y: rect.midY),
radius: rect.height / 2,
startAngle: Angle(degrees: 0),
endAngle: Angle(degrees: 180),
clockwise: false)
path.addLine(to: CGPoint(x: rect.minX, y: rect.midY))
}
}
}
struct QuadSample: Shape {
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: .zero)
path.addQuadCurve(to: CGPoint(x: rect.midX, y: rect.midY),
control: CGPoint(x: rect.maxX - 50, y: rect.minY - 100))
}
}
}
struct WaterShape: Shape {
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: rect.minX, y: rect.midY))
path.addQuadCurve(to: CGPoint(x: rect.midX, y: rect.midY),
control: CGPoint(x: rect.width * 0.25, y: rect.height * 0.40))
path.addQuadCurve(to: CGPoint(x: rect.maxX, y: rect.midY),
control: CGPoint(x: rect.width * 0.75, y: rect.height * 0.60))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
}
}
}
struct CustomCurversBootCamp: View {
var body: some View {
WaterShape()
.fill(
LinearGradient(gradient: Gradient(colors: [.blue, .indigo, .cyan]), startPoint: .topLeading, endPoint: .bottomTrailing)
)
.ignoresSafeArea()
}
}
move
가 특정 위치로 점을 이동하는 함수addLine
: 현재 위치에서 해당 위치까지 직선을 그리는 함수addArc
: 호의 중앙, 시작 각도, 끝나는 각도, 호를 그리는 방향addQuadCurve
: 이차 함수의 볼록 곡선을 그리는 함수. 현재 위치부터 to
까지 control
상태의 곡선을 그림.
addQuadCurve
를 통해 매우 다양한 곡선을 추가할 수 있는데, 이때 주어진 프레임의 높이/너비 등에 특정 값을 곱해 사용하는 것 같다.