如何在iOS图表中仅呈现选定的轴标签

3

我使用的库是:charts
我有一个带有特定年份中某些日期值的折线图。我不想在x轴上绘制每一天的标签(可能超过300天的范围),所以我想只绘制月份。现在,我的xVals看起来像:[nil, nil, nil, "07/2016", nil nil nil (..)]。不幸的是,没有标签显示。
有没有其他方法可以实现所需的行为?

代码(x轴值):

while date.compare(to) != NSComparisonResult.OrderedDescending { // iterate over all days in range
        let components = currentCalendar.components([.Day, .Month , .Year], fromDate: date)
        if components.day != 1 {
            vals.append(nil)
        } else { // first day of the month
            vals.append(String(components.month) + " / " + String(components.year))
        }

        let incrementComponents = NSDateComponents()
        incrementComponents.day = 1
        date = currentCalendar.dateByAddingComponents(incrementComponents, toDate: date, options: [])!
}

并且条目:

for point in base!.points {
        if let index = chartValuesFormatter?.indexFromDate(point.date) {
            entries.append(ChartDataEntry(value: point.value, xIndex: index))
        }
}

通常情况下,当我指定所有值时,它可以工作,其中一些值会显示并且条目被正确渲染。我的唯一问题是只在月初显示月标签。


但有时它会重复显示同一个月份。我需要在每个月的第一天显示月份标签(如果有太多的月份,则可以更少地显示 - 这是库应该自行优化的内容)。 - Maciej Kozieł
请问您能否粘贴一些关于如何创建数据的代码? - Jassi
@Jassi 添加了代码示例 - Maciej Kozieł
哦,对了,可能需要用那些 nil 和 "" 值来替换长文本。 - Tj3n
让我们在聊天中继续这个讨论 - Maciej Kozieł
显示剩余5条评论
1个回答

2

好的,我已经找到了解决方案。对于这样基本的问题来说,它并不像应该那样简单,但是它非常可定制。 LineChartView(通过BarLineChartViewBase)具有属性xAxisRenderer。您可以对ChartXAxisRenderer进行子类化,它是默认的一个,并重写drawLabels函数。在我的情况下,我复制了原始代码,并修改了在哪里绘制标签以及应该绘制哪个标签的逻辑。

编辑:我的自定义渲染器具有重叠逻辑。可能过于复杂,但目前为止它可以工作。

class ChartXAxisDateRenderer: ChartXAxisRenderer {
internal static let FDEG2RAD = CGFloat(M_PI / 180.0)

/// draws the x-labels on the specified y-position
override func drawLabels(context context: CGContext, pos: CGFloat, anchor: CGPoint) {

    guard let xAxis = xAxis else { return }

    let paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
    paraStyle.alignment = .Center

    let labelAttrs = [NSFontAttributeName: xAxis.labelFont,
                      NSForegroundColorAttributeName: xAxis.labelTextColor,
                      NSParagraphStyleAttributeName: paraStyle]
    let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartXAxisDateRenderer.FDEG2RAD

    let valueToPixelMatrix = transformer.valueToPixelMatrix

    let minLabelsMargin: CGFloat = 4.0

    var position = CGPoint(x: 0.0, y: 0.0)

    var labelMaxSize = CGSize()

    if (xAxis.isWordWrapEnabled) {
        labelMaxSize.width = xAxis.wordWrapWidthPercent * valueToPixelMatrix.a
    }

    var positions = [CGPoint]()
    var widths = [CGFloat]()
    var labels = [String]()
    var originalIndices = [Int]()

    for i in 0...xAxis.values.count-1 {
        let label = xAxis.values[i]
        if (label == nil || label == "")
        {
            continue
        }

        originalIndices.append(i)
        labels.append(label!)

        position.x = CGFloat(i)
        position.y = 0.0
        position = CGPointApplyAffineTransform(position, valueToPixelMatrix)
        positions.append(position)

        let labelns = label! as NSString
        let width = labelns.boundingRectWithSize(labelMaxSize, options: .UsesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width
        widths.append(width)
    }

    let newIndices = findBestPositions(positions, widths: widths, margin: minLabelsMargin)

    for index in newIndices {
        let label = labels[index]
        let position = positions[index]
        let i = originalIndices[index]

        if (viewPortHandler.isInBoundsX(position.x)) {
            drawLabel(context: context, label: label, xIndex: i, x: position.x, y: pos, attributes: labelAttrs, constrainedToSize: labelMaxSize, anchor: anchor, angleRadians: labelRotationAngleRadians)
        }
    }
}

// Best position indices - minimum "n" without overlapping
private func findBestPositions(positions: [CGPoint], widths: [CGFloat], margin: CGFloat) -> [Int] {
    var n = 1
    var overlap = true

    // finding "n"
    while n < widths.count && overlap {
        overlap = doesOverlap(n, positions: positions, widths: widths, margin: margin)
        if overlap {
            n += 1
        }
    }

    var newPositions = [Int]()
    var i = 0
    // create result indices
    while i < positions.count {
        newPositions.append(i)
        i += n
    }

    return newPositions
}

// returns whether drawing only n-th labels will casue overlapping
private func doesOverlap(n: Int, positions: [CGPoint], widths: [CGFloat], margin: CGFloat) -> Bool {
    var i = 0
    var newPositions = [CGPoint]()
    var newWidths = [CGFloat]()

    // getting only n-th records
    while i < positions.count {
        newPositions.append(positions[i])
        newWidths.append(widths[i])
        i += n
    }

    // overlap with next label checking
    for j in 0...newPositions.count - 2 {
        if newPositions[j].x + newWidths[j] + margin > newPositions[j+1].x {
            return true
        }
    }

    return false
}

}


抱歉给您带来不便,但我遇到了同样的问题,您能否发布您的自定义代码?谢谢! - user3745888
@user3745888发布了。大部分代码都是关于重叠的,但其余部分应该很清楚。我猜它有缺陷和过度复杂(还没有经过充分的测试)。欢迎留下评论。 - Maciej Kozieł

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接