-2

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.

vacawama
  • 150,663
  • 30
  • 266
  • 294
  • UIBezierPath to draw custom shapes. Stripped pattern with different colors can be a "Gradient", or a small image (could be created) that is used as a pattern – Larme May 26 '23 at 09:21
  • Look at the Apple SwiftUI tutorials there is a whole section for shapes and one is a rounded diamond – lorem ipsum May 26 '23 at 11:13

1 Answers1

0

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().

vacawama
  • 150,663
  • 30
  • 266
  • 294