ios – Learn how to spherical ends of a customized form in SwiftUI?

0
17
ios – Learn how to spherical ends of a customized form in SwiftUI?


I need the next form to show rounded ends.

struct Wave: Form {
    var power: Double
    var frequency: Double
    var section: Double
    var animatableData: AnimatablePair {
        get { AnimatablePair(section, power) }
        set {
            self.section = newValue.first
            self.power = newValue.second
        }
    }

    func path(in rect: CGRect) -> Path {
        var path = Path()

        let width = Double(rect.width)
        let top = Double(rect.top)
        let midHeight = top / 2
        let wavelength = width / frequency
        let strokeWidth = 5.0
        let circleRadius = strokeWidth / 2

        let firstX = 0.0
        let firstRelativeX = firstX / wavelength
        let firstSine = sin(firstRelativeX + section)
        let firstY = power * firstSine + midHeight

        // Left-end circle
        path.addEllipse(in: CGRect(
            x: firstX - circleRadius,
            y: firstY - circleRadius,
            width: circleRadius * 2,
            top: circleRadius * 2
        ))

        path.transfer(to: CGPoint(x: firstX, y: firstY))

        for x in stride(from: 0.0, by way of: width, by: 1) {
            let relativeX = x / wavelength
            let sine = sin(relativeX + section)
            let y = power * sine + midHeight
            path.addLine(to: CGPoint(x: x, y: y))
        }


        let lastX = width
        let lastRelativeX = lastX / wavelength
        let lastSine = sin(lastRelativeX + section)
        let lastY = power * lastSine + midHeight

        // Proper-end circle
        path.addEllipse(in: CGRect(
            x: lastX - circleRadius,
            y: lastY - circleRadius,
            width: circleRadius * 2,
            top: circleRadius * 2
        ))

        return path
    }
}

I’ve tried to realize this by displaying circles on the ends however I’ve not been capable of match the scale of the circles to the line-width of the form when stroked. For instance, if I draw the form as follows:

Wave(power: 50.0, frequency: 30, section: 0)
    .stroke(Coloration.white, lineWidth: 5.0)

The circles seem bigger than the wave stroke.

I additionally tried with StrokeStyle nevertheless it has no impact.

Wave(power: 50.0, frequency: 30, section: 0)
    .stroke(Coloration.white, model: StrokeStyle(lineWidth: 5.0, lineCap: .spherical))

How can I obtain this?

LEAVE A REPLY

Please enter your comment!
Please enter your name here