菜鸟教程小白 发表于 2022-12-11 17:13:04

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


                                            <p><p>我正在使用的库:<a href="https://github.com/danielgindi/Charts" rel="noreferrer noopener nofollow">charts</a> <br/>
我有一年中特定日期的值的折线图。我不想把每一天都画成 x 轴上的标签(可能有超过 300 天的范围),所以我只想画几个月。现在,我的 xVals 看起来像:。很遗憾,没有显示任何标签。<br/>
有没有其他方法可以实现所需的行为?
<br/>
<br/>
代码(x 轴值):<br/></p>

<pre><code>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) + &#34; / &#34; + String(components.year))
      }

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

<p>和条目:</p>

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

<p>通常它可以工作,当我指定所有值时,其中一些会显示并且条目会正确呈现。我唯一的问题是在月初只显示月份标签。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>好的,我找到了解决方案。它并不像应该的那样简单(对于这样的基本问题),但非常可定制。
<code>LineChartView(通过 BarLineChartViewBase)</code> 具有属性 <code>xAxisRenderer</code>。您可以继承默认的 <code>ChartXAxisRenderer</code>,并覆盖 <code>drawLabels</code> 函数。在我的例子中,我复制了原始代码并修改了计算应该绘制什么标签和在哪里绘制的逻辑。</p>

<p>编辑:我的自定义渲染器具有重叠逻辑。可能过于复杂,但到目前为止它仍然有效。</p>

<pre><code>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 = ()
    var widths = ()
    var labels = ()
    var originalIndices = ()

    for i in 0...xAxis.values.count-1 {
      let label = xAxis.values
      if (label == nil || label == &#34;&#34;)
      {
            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
      let position = positions
      let i = originalIndices

      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 &#34;n&#34; without overlapping
private func findBestPositions(positions: , widths: , margin: CGFloat) -&gt; {
    var n = 1
    var overlap = true

    // finding &#34;n&#34;
    while n &lt; widths.count &amp;&amp; overlap {
      overlap = doesOverlap(n, positions: positions, widths: widths, margin: margin)
      if overlap {
            n += 1
      }
    }

    var newPositions = ()
    var i = 0
    // create result indices
    while i &lt; 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: , widths: , margin: CGFloat) -&gt; Bool {
    var i = 0
    var newPositions = ()
    var newWidths = ()

    // getting only n-th records
    while i &lt; positions.count {
      newPositions.append(positions)
      newWidths.append(widths)
      i += n
    }

    // overlap with next label checking
    for j in 0...newPositions.count - 2 {
      if newPositions.x + newWidths + margin &gt; newPositions.x {
            return true
      }
    }

    return false
}
</code></pre>

<p>}</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何在 ios 图表中仅呈现选定的轴标签,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/38847938/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/38847938/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何在 ios 图表中仅呈现选定的轴标签