drawRuler method

void drawRuler(
  1. Canvas canvas,
  2. Paint paint
)

x,y轴刻度 & 辅助线

Implementation

void drawRuler(Canvas canvas, Paint paint) {
  if (chartBeans?.isEmpty ?? true) return;
  int length = min(7, chartBeans!.length); //最多绘制7个
  double dw = _fixedWidth / (length - 1); //两个点之间的x方向距离
  double dh = _fixedHeight / (length - 1); //两个点之间的y方向距离
  for (int i = 0; i < length; i++) {
    ///绘制x轴文本
    TextPainter(
      ellipsis: '.',
      textAlign: TextAlign.center,
      text: TextSpan(
        text: chartBeans![i].x,
        style: TextStyle(color: fontColor, fontSize: fontSize),
      ),
      textDirection: TextDirection.ltr,
    )
      ..layout(minWidth: 40)
      ..paint(canvas, Offset(startX + dw * i - 20, startY + basePadding));

    if (isShowHintX) {
      ///x轴辅助线
      canvas.drawLine(
          Offset(startX, startY - dh * i),
          Offset(endX + basePadding, startY - dh * i),
          paint..color = paint.color.withOpacity(0.5));
    }

    if (isShowHintY) {
      // y轴辅助线
      canvas.drawLine(
        Offset(startX + dw * i, startY),
        Offset(startX + dw * i, endY - basePadding),
        paint,
      );
    }

    if (!isShowXyRuler) continue;

    // x轴刻度
    canvas.drawLine(
      Offset(startX + dw * i, startY),
      Offset(startX + dw * i, startY - rulerWidth),
      paint,
    );
  }
  int yLength = yNum! + 1; //包含原点,所以 +1
  double dValue = maxMin[0] / yNum!; //一段对应的值
  double dV = _fixedHeight / yNum!; //一段对应的高度
  for (int i = 0; i < yLength; i++) {
    if (isShowYValue) {
      // 绘制y轴文本,保留1位小数
      var yValue = (dValue * i).toStringAsFixed(isShowFloat! ? 1 : 0);
      TextPainter(
        textAlign: TextAlign.center,
        ellipsis: '.',
        maxLines: 1,
        textDirection: TextDirection.rtl,
        text: TextSpan(
          text: '$yValue',
          style: TextStyle(color: fontColor, fontSize: fontSize),
        ),
      )
        ..layout(minWidth: 40)
        ..paint(
          canvas,
          Offset(startX - 40, startY - dV * i - fontSize! / 2),
        );
    }

    if (!isShowXyRuler) continue;

    // y轴刻度
    canvas.drawLine(
      Offset(startX, startY - dV * (i)),
      Offset(startX + rulerWidth, startY - dV * (i)),
      paint,
    );
  }
}