aboutsummaryrefslogtreecommitdiff
path: root/lib/widgets/common/basic/text/background_painter.dart
blob: e3757c1b860cd6d7f1915456ca151b907b8d4377 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import 'dart:ui' as ui;

import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

// as of Flutter v3.3.7, text style background does not have consistent height
// when rendering multi-script text, so we paint the background behind via a stack instead
class TextBackgroundPainter extends StatelessWidget {
  final List<TextSpan> spans;
  final TextStyle style;
  final TextAlign textAlign;
  final Widget child;

  const TextBackgroundPainter({
    super.key,
    required this.spans,
    required this.style,
    required this.textAlign,
    required this.child,
  });

  @override
  Widget build(BuildContext context) {
    final backgroundColor = style.backgroundColor;
    if (backgroundColor == null || backgroundColor.a == 0) {
      return child;
    }

    return LayoutBuilder(
      builder: (context, constraints) {
        final paragraph = RenderParagraph(
          TextSpan(
            children: spans,
            style: style,
          ),
          textAlign: textAlign,
          textDirection: Directionality.of(context),
          textScaler: MediaQuery.textScalerOf(context),
        )..layout(constraints, parentUsesSize: true);

        final textLength = spans.map((v) => v.text?.length ?? 0).sum;
        final allBoxes = paragraph.getBoxesForSelection(
          TextSelection(baseOffset: 0, extentOffset: textLength),
          boxHeightStyle: ui.BoxHeightStyle.max,
        );
        paragraph.dispose();

        // merge boxes to avoid artifacts at box edges, from anti-aliasing and rounding hacks
        final lineRects = groupBy<TextBox, double>(allBoxes, (v) => v.top).entries.map((kv) {
          final top = kv.key;
          final lineBoxes = kv.value;
          return Rect.fromLTRB(
            lineBoxes.map((v) => v.left).min,
            top,
            lineBoxes.map((v) => v.right).max,
            lineBoxes.first.bottom,
          );
        });

        return Stack(
          children: [
            ...lineRects.map((rect) {
              return Positioned.fromRect(
                rect: rect,
                child: ColoredBox(
                  color: backgroundColor,
                ),
              );
            }),
            child,
          ],
        );
      },
    );
  }
}