如何在iOS图表中添加最大值和最小值的箭头?

时间:2018-03-20 10:36:36

标签: ios-charts

我想显示最大值和最小值的箭头,如下图所示。

有没有人有关于如何使用iOS-Charts实现它的想法?非常感谢。

Chart description

1 个答案:

答案 0 :(得分:0)

您需要为CandleStickChartView编写自己的自定义渲染器。 幸运的是,在您的情况下,您只需要覆盖一种方法。

因此,从CandleStickChartRenderer继承类并覆盖方法drawValues(context: CGContext)。您只需从父方法中复制/粘贴大部分代码,只进行必要的更改。

class MyCandleStickChartRenderer: CandleStickChartRenderer {

    internal var _xBounds = XBounds()

    var minValue: Double
    var maxValue: Double

    init (view: CandleStickChartView, minValue: Double, maxValue: Double) {
        self.minValue = minValue
        self.maxValue = maxValue

        super.init(dataProvider: view, animator: view.chartAnimator, viewPortHandler: view.viewPortHandler)
    }

    override func drawValues(context: CGContext)
    {
        // ... I remove some code that was not changed ...

            for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
            {
                guard let e = dataSet.entryForIndex(j) as? CandleChartDataEntry else { break }

                // need to show only min and max values
                guard e.high == maxValue || e.low == minValue else { continue }

                pt.x = CGFloat(e.x)
                if e.high == maxValue {
                    pt.y = CGFloat(e.high * phaseY)
                } else if e.low == minValue {
                    pt.y = CGFloat(e.low * phaseY)
                }
                pt = pt.applying(valueToPixelMatrix)

                // ... I remove some code that was not changed ...   

                if dataSet.isDrawValuesEnabled
                {
                    var textValue: String?
                    var align: NSTextAlignment = .center

                    // customize position for min/max value 
                    if e.high == maxValue {
                        pt.y -= yOffset
                        textValue = "←  " + String(maxValue)
                        align = .left
                    } else if e.low == minValue {
                        pt.y += yOffset / 5
                        textValue = String(minValue) + "  →"
                        align = .right
                    }

                    if let textValue = textValue {
                        ChartUtils.drawText(
                            context: context,
                            text: textValue,
                            point: CGPoint(
                                x: pt.x,
                                y: pt.y ),
                            align: align,
                            attributes: [NSAttributedStringKey.font: valueFont, NSAttributedStringKey.foregroundColor: dataSet.valueTextColorAt(j)])
                    }
                }
            }
        }
    }
}

您还需要创建渲染器的实例,并在图表视图中将其设置为属性。

myCandleStickChartView.renderer = MyCandleStickChartRenderer(view: candleStickChartView, minValue: 400, maxValue: 1450)

最后......

enter image description here