drawForeground method

  1. @override
void drawForeground(
  1. Canvas canvas,
  2. Size size
)
override

Draws the foreground elements of the chart after background drawing.

Implementation

@override
void drawForeground(Canvas canvas, Size size) {
  if (states.isEmpty) return;

  final maxWidth = size.width - constraint.width;
  final maxHeight = size.height - constraint.height - (separatedBorderWidth * barRatio);
  final areaWidth = maxWidth / states.length;
  final barWidth = areaWidth * barRatio;

  for (int i = 0; i < states.length; i++) {
    final target = states[i];
    final height = ((target.value * fadePercent) / maxValue) * maxHeight;

    // About the position of a bar.
    final color = ChartColor.hoverOf(target.data.color ?? barColor, target.hover, 0.2);
    final startX = constraint.left + (areaWidth * i) + (areaWidth - barWidth) / 2;
    final startY = maxHeight - height;
    final paint = Paint()..color = color;
    final rrect = barBorderRadius.toRRect(Rect.fromLTRB(startX, startY, startX + barWidth, maxHeight));

    target.position = ChartPosition(path: Path()..addRRect(rrect));
    canvas.drawRRect(rrect, paint);

    if (isVisibleBarText) {
      final text = "${target.value.round()}";
      final textPainter = TextPainter(
        text: TextSpan(text: text, style: defaultTextStyle.merge(
              barTextAlignment == ChartBarTextAlignment.inner_center
           || barTextAlignment == ChartBarTextAlignment.inner_leading
           || barTextAlignment == ChartBarTextAlignment.inner_trailing
           ? barInnerTextStyle(target)
           : barOuterTextStyle(target)
        )),
        textDirection: TextDirection.ltr,
      );

      textPainter.layout(maxWidth: maxWidth);

      final textWidth = textPainter.width;
      final textHeight = textPainter.height;
      final textStartX = startX + (barWidth - textWidth) / 2;

      // Not drawing when overflow in layout calculation for the bar text.
      if (isInnerBarTextAlignment && height < textHeight + barInnerTextMargin * 2) {
        continue;
      }

      switch (barTextAlignment) {
        case ChartBarTextAlignment.inner_center:
          textPainter.paint(canvas, Offset(textStartX, startY + height / 2));
          break;

        case ChartBarTextAlignment.inner_leading:
          textPainter.paint(canvas, Offset(textStartX, startY + barInnerTextMargin));
          break;

        case ChartBarTextAlignment.inner_trailing:
          textPainter.paint(canvas, Offset(textStartX, (startY + height) - textHeight - barInnerTextMargin));
          break;

        case ChartBarTextAlignment.outer:
          textPainter.paint(canvas, Offset(textStartX, (startY - textHeight) - barOuterTextMargin));
          break;
      }
    }
  }
}