path.fit()
將 Path 塞到另一個 CGRect 中。
Last updated
將 Path 塞到另一個 CGRect 中。
Last updated
// ⭐️ required:
// - 🅿️ Vector2D
// - 🌀 Path + transform
import SwiftUI
import VectorSpace // for `-v` additive inverse
extension Path {
// path.fit(in: rect)
public func fit(in rect: CGRect) -> Path {
// scale factors
let x = rect.width / boundingRect.width
let y = rect.height / boundingRect.height
// fit self into rect
return self
.translate(-boundingRect.origin) // 🅿️ Vector2D, 🌀Path + transform
.dilate(x, y) // 🌀Path + transform
.translate(rect.origin)
}
}
/*
* ⭐️ required:
* - 🌀Path + fit
* - 🅿️ Vector2D
* - 📦 Fit
*/
import SwiftUI
import PlaygroundSupport
// paths
let balloon = Path { p in
p.move (to: [ 50, 0]) // 🅿️ Vector2D
p.addQuadCurve(to: [ 0, 50], control : [ 0, 0])
p.addCurve (to: [ 50, 150], control1: [ 0, 100], control2: [ 50, 100])
p.addCurve (to: [100, 50], control1: [ 50, 100], control2: [100, 100])
p.addQuadCurve(to: [ 50, 0], control : [100, 0])
}
let square = Path { p in
p.move(to: [50, 50])
p.addLines([[100, 50], [100,100], [50, 100], [50, 50]])
p.closeSubpath()
}
let diamond = Path { p in
p.move(to: [50, 50])
p.addLines([[100, 100], [50,150], [0, 100], [50, 50]])
p.closeSubpath()
}
diamond.boundingRect
// live view
struct ContentView: View {
var body: some View {
HStack {
Group {
Fit(balloon) // 📦Fit
Fit(square)
Fit(diamond)
diamond
.fit(in: CGRect(50, 0, 50, 100)) // 🌀Path + fit
.stroke()
} // Group
.overlay(Rectangle().stroke(Color.gray, style: .init(dash: [6])))
} // VStack (container)
.padding()
.border(Color.gray, width: 3)
.frame(height: 200)
}
}
PlaygroundPage.current.setLiveView(ContentView())
🌀Path + .transform