Created
March 11, 2023 04:33
-
-
Save samsonjs/a8be63a4dbbef3e8b1e2254951601d8c to your computer and use it in GitHub Desktop.
Zigzag border view for SwiftUI, but it doesn't look very good
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
/// Mostly courtesy of ChatGPT but even with some coaching it couldn't get it to the finish line. Humans are still useful! It's still ugly though. | |
struct ZigzagBorder: Shape { | |
let lineWidth: CGFloat | |
let amplitude: CGFloat | |
func path(in rect: CGRect) -> Path { | |
var path = Path() | |
let startX = rect.minX | |
let endX = rect.maxX | |
let startY = rect.minY | |
let endY = rect.maxY | |
let xSteps = Int((endX - startX) / amplitude / 2) | |
let ySteps = Int((endY - startY) / amplitude / 2) | |
// Top border | |
path.move(to: CGPoint(x: startX, y: startY)) | |
for i in 0...xSteps { | |
let x = startX + amplitude * CGFloat(i * 2) | |
path.addLine(to: CGPoint(x: x, y: startY + (i % 2 == 1 ? amplitude : 0))) | |
} | |
path.addLine(to: CGPoint(x: endX, y: startY)) | |
// Right border | |
path.move(to: CGPoint(x: endX, y: startY)) | |
for i in 0...ySteps { | |
let y = startY + amplitude * CGFloat(i * 2) | |
path.addLine(to: CGPoint(x: endX - (i % 2 == 1 ? amplitude : 0), y: y)) | |
} | |
path.addLine(to: CGPoint(x: endX, y: endY)) | |
// Bottom border | |
path.move(to: CGPoint(x: startX, y: endY)) | |
for i in 0...xSteps { | |
let x = startX + amplitude * CGFloat(i * 2) | |
path.addLine(to: CGPoint(x: x, y: endY - (i % 2 == 1 ? amplitude : 0))) | |
} | |
path.addLine(to: CGPoint(x: endX, y: endY)) | |
// Left border | |
path.move(to: CGPoint(x: startX, y: startY)) | |
for i in 0...ySteps { | |
let y = startY + amplitude * CGFloat(i * 2) | |
path.addLine(to: CGPoint(x: startX + (i % 2 == 1 ? amplitude : 0), y: y)) | |
} | |
path.addLine(to: CGPoint(x: startX, y: endY)) | |
return path.strokedPath(.init(lineWidth: lineWidth, lineCap: .round, lineJoin: .round)) | |
} | |
} | |
struct ZigZagBorder_Previews: PreviewProvider { | |
static var previews: some View { | |
VStack(spacing: 32) { | |
Text("Mostly written by ChatGPT") | |
.padding() | |
.background { | |
ZigzagBorder(lineWidth: 2, amplitude: 2) | |
.foregroundColor(.accentColor) | |
} | |
Text("Mostly written by ChatGPT") | |
.padding() | |
.background { | |
ZigzagBorder(lineWidth: 2, amplitude: 6) | |
.foregroundColor(.accentColor) | |
} | |
Text("Mostly written by ChatGPT") | |
.padding() | |
.background { | |
ZigzagBorder(lineWidth: 5, amplitude: 10) | |
.foregroundColor(.accentColor) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment