Core Graphics Graph lines not drawing

时间:2018-02-26 17:55:25

标签: ios swift core-graphics

I'm using this code to try to build my own graph using Core Graphics, it all works well except the horizontal lines and X and Y axises are not drawing (on the storyboard or in the simulator) and I cannot see anything in the code that would prohibit them from drawing? Relevant code below:

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

1 个答案:

答案 0 :(得分:2)

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

33.3%