【问题标题】:Make edges on graph line round and not "sharp" Swiftui使图形线上的边缘圆润而不是“锋利” Swiftui
【发布时间】:2021-03-11 19:47:04
【问题描述】:

我目前正在开发一个小部件的图形视图,我不喜欢边缘在我的图形 atm 上的显示方式。我想让我的图表线上的边缘变圆而不是尖锐(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 []
    }
}

【问题讨论】:

  • 我无法运行你的代码,ViewStyling()是什么?

标签: ios swift graph swiftui


【解决方案1】:

如何渲染线段之间的连接由StrokeStylelineJoin 属性控制,您在这里用颜色和线宽进行描边:

.stroke(styling.graphLine, lineWidth: 2)

但你想要的更像是:

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

【讨论】:

  • 我用过这个。 lineJoin 中的所有选项根本不起作用。他们总是表现出尖角。我正在使用 swift5,iOS 15。有没有人有这个解决方案?谢谢
  • 也使用了这个.stroke(style: StrokeStyle(lineWidth: 2, lineCap: .round)),但没有成功
  • @lopes710 请单独提问
猜你喜欢
  • 1970-01-01
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-06
  • 2022-09-28
  • 1970-01-01
相关资源
最近更新 更多