使图形线上的边缘变圆而不是“锐利”的 Swiftui

时间:2021-03-11 11:10:50

标签: ios swift graph swiftui

我目前正在处理小部件的图形视图,但我不喜欢边在我的图形自动取款机上的外观。我想让我的图形线上的边缘变圆而不是锐利 (Graph)。 我尝试过 .cornerRadius(5) 和 .addQuadCurve() 但似乎没有任何效果。

我的代码看起来像这样。

import SwiftUI

@available(iOS 14.0.0, *)

struct Graph: View {

    var styling = ViewStyling()
    var stockPrices: [CGFloat]

    var body: some View {
        ZStack {
            LinearGradient(gradient:
                        Gradient(colors: [styling.gradientColor, styling.defaultWhite]), startPoint: .top, endPoint: .bottom)
            .clipShape(LineGraph(dataPoints: stockPrices.normalized, closed: true))

        LineGraph(dataPoints: stockPrices.normalized)
            .stroke(styling.graphLine, lineWidth: 2)
            //.cornerRadius(5)
        }
    }
}

@available(iOS 14.0.0, *)
struct LineGraph: Shape {
    var dataPoints: [CGFloat]
    var closed = false

    func path(in rect: CGRect) -> Path {
    
        func point(at ix: Int) -> CGPoint {
            let point = dataPoints[ix]
            let x = rect.width * CGFloat(ix) / CGFloat(dataPoints.count - 1)
            let y = (1 - point) * rect.height
        
            return CGPoint(x: x, y: y)
        }
    
        return Path { p in
        
            guard dataPoints.count > 1 else { return }
        
            let start = dataPoints[0]
            p.move(to: CGPoint(x: 0, y: (1 - start) * rect.height))
            //p.addQuadCurve(to: CGPoint(x: rect.maxX, y: rect.maxY), control: CGPoint(x: rect.maxX, y: rect.maxY))
        
            for index in dataPoints.indices {
                 p.addLine(to: point(at: index))
            }

            if closed {
                p.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
                p.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
                p.closeSubpath()
            }
        }
    }
}

extension Array where Element == CGFloat {
    // Return the elements of the sequence normalized.
    var normalized: [CGFloat] {
        if let min = self.min(), let max = self.max() {
            return self.map{ ($0 - min) / (max - min) }
        }
        return []
    }
}

1 个答案:

答案 0 :(得分:1)

如何呈现线段之间的连接由 lineJoinStrokeStyle 属性控制,您在此处使用颜色和线宽进行描边:

.stroke(styling.graphLine, lineWidth: 2)

但你想要更像:

.stroke(styling.graphline, StrokeStyle(lineWidth: 2, lineJoin: .round))