.grids()
這是一個 Shape,用來當設計時輔助用的「格線」,每個小間隔是 10 points,大間格為 50 points。
Last updated
這是一個 Shape,用來當設計時輔助用的「格線」,每個小間隔是 10 points,大間格為 50 points。
Last updated
下面我們設計了一個 📦 Grids,它是一個 🅿️ Shape,裡面畫了水平格線與垂直格線。
接著,我們又設計了一個 🅿️ View 的擴展,讓我們可以利用:view.grids() 的方式,幫任何一個 view 加格線,詳細的語法請看下面的「🌀 View + .grids()」分頁。
/*
* ⭐️ Required: 📦 Grids
*/
import SwiftUI
// 🌀View + .grids(color, opacity, overlay)
extension View {
/// # Grid Lines
/// draw grid lines behind or in front of a view.
/// - Parameters:
/// - color: grid line color (default = `.gray`).
/// - opacity: grid line's opacity. (default = `0.4`)
/// - overlay: if `true`, draw in front of the view. (default = `false`)
public func grids(
_ color: Color = Color.gray,
opacity : Double = 0.4,
overlay : Bool = false
) -> some View {
// line color and dash line style
let color = color.opacity(opacity)
let dash = StrokeStyle(dash: [1])
// draw grids
return Group {
if overlay {
self
.overlay(Grids().stroke(color, style: dash)) // 📦 Grids
.overlay(Grids(50).stroke(color))
} else {
self
.background(Grids(50).stroke(color))
.background(Grids().stroke(color, style: dash))
}
}
}
}
/*
* ⭐️ Required: 🅿️ Vector2D
*/
import SwiftUI
// 📦 Grids
public struct Grids: Shape {
let distance: CGFloat // distance between grids
// init
public init(_ distance: CGFloat = 10) {
self.distance = distance
}
public func path(in rect: CGRect) -> Path {
// related dimensions
let w = rect.width
let h = rect.height
let d = distance
let M = Int(w / d)
let N = Int(h / d)
// draw path
return Path { path in
// vertical lines
for i in 0 ... M {
let x = CGFloat(i) * d
path.move (to: [x, 0])
path.addLine(to: [x, h])
}
// horizontal lines
for i in 0 ... N {
let y = CGFloat(i) * d
path.move (to: [0, y])
path.addLine(to: [w, y])
}
}
}
}
struct ContentView: View {
var body: some View {
VStack {
Rectangle()
.fill(Color.gray)
.grids(.black, overlay: true)
.frame(width: 200, height: 150)
}
}
}