Striped pattern for a custom shape in swift UI

375 Views Asked by At

I am learning Swift with the cs193p online class https://cs193p.sites.stanford.edu/.

One of the assignment entails creating a custom shape (like a diamond) and then applying a striped pattern to its background (with different colors).

I was wondering whats a good way to approach this (without using images if possible). Looked around quite a bit but don't even know where to start. In general, is there any way

Googled around a bit but couldn't find any good solutions.

1

There are 1 best solutions below

0
vacawama On

Here is one way to do it. Create a Shape called Stripes:

struct Stripes: Shape {
    
    func path(in rect: CGRect) -> Path {
        var path = Path()
        let width = rect.size.width
        let height = rect.size.height
        
        for x in stride(from: 0, through: width, by: width / 9) {
            path.move(to: CGPoint(x: x, y: 0))
            path.addLine(to: CGPoint(x: x, y: height))
        }
        return path
    }
}

Then when you are drawing a striped shape:

ZStack {
    // Draw the stripes clipped to the shape
    Stripes()
        .stroke(lineWidth: 2 * scale)
        .clipShape(shape)

    // Draw the shape outline
    shape.stroke(lineWidth: 4 * scale)
}
.frame(width: 150, height: 100)

where scale is a CGFloat that you'll want to vary depending on the size of the shape that you are drawing. Start with a value of 1.0 and make it larger to get the right look. shape is one of Rectangle(), Capsule(), or Diamond().