核心图形图线不绘制

Core Graphics Graph lines not drawing

我正在使用 this 代码尝试使用 Core Graphics 构建我自己的图表,除了水平线和 X 轴和 Y 轴未绘制(在故事板或模拟器中)外,一切正常) 而且我在代码中看不到任何禁止他们绘图的内容?相关代码如下:

   override func draw(_ rect: CGRect) {
        super.draw(rect)

        context = UIGraphicsGetCurrentContext()

        // Graph size
        graphWidth = (rect.size.width - padding) - 10
        graphHeight = rect.size.height - 40
        axisWidth = rect.size.width - 10
        axisHeight = (rect.size.height - padding) - 10

        // Lets work out the highest value and round to the nearest 25.
        // This will be used to work out the position of each value
        // on the Y axis, it essentialy reperesents 100% of Y
        for (index, point) in data.enumerated() {
            let keys = Array(data[index].keys)
            let currKey = keys.first!
            if CGFloat(point[currKey]!) > everest {
                everest = CGFloat(Int(ceilf(Float(point[currKey]!) / 25) * 25))
            }
        }
        if everest == 0 {
            everest = 25
        }

        // Draw graph X-AXIS
        let xAxisPath = CGMutablePath()
        xAxisPath.move(to: CGPoint(x: padding, y: rect.size.height - 31))
        xAxisPath.move(to: CGPoint(x: axisWidth, y: rect.size.height - 31))
        context!.addPath(xAxisPath)

        context!.setStrokeColor(xAxisColor.cgColor)
        context!.strokePath()

        // Draw graph Y-AXIS
        let yAxisPath = CGMutablePath()
        yAxisPath.move(to: CGPoint(x: padding, y: 10))
        yAxisPath.move(to: CGPoint(x: padding, y: rect.size.height - 31))
        context!.addPath(yAxisPath)

        context!.setStrokeColor(yAxisColor.cgColor)
        context!.strokePath()

     let yLabelInterval : Int = Int(everest / 5)
            for i in 0...5 {

                let label = axisLabel(title: String(format: "%d", i * yLabelInterval))
                label.frame = CGRect(x: 0, y: floor((rect.size.height - padding) - CGFloat(i) * (axisHeight / 5) - 10), width: 30, height: 20) //I changed width from 20 to 30
                addSubview(label)


                if(showLines && i != 0) {
                    let line = CGMutablePath()
                    line.move(to: CGPoint(x: padding + 1, y: floor(rect.size.height - padding) - (CGFloat(i) * (axisHeight / 5))))
                    line.move(to: CGPoint(x: axisWidth, y: floor(rect.size.height - padding) - (CGFloat(i) * (axisHeight / 5))))
                    context!.addPath(line)
                    context!.setStrokeColor(linesColor.cgColor)
                    context!.strokePath()
                }
            }

我在swift 4中测试了你的代码。没有显示轴线。另一种方法是,您可以使用如下所示的 "addLines" 函数。

xAxisPath.addLines(between: [CGPoint(x: padding, y: rect.size.height - 31), CGPoint(x: axisWidth, y: rect.size.height - 31)])