drawText method
Draws the context (label) of a plotband.
Allows a complete customization of bespoke typography, dynamic positioning, drop shadows, or interactive effects.
position represents the top-left origin of the text.
angle is the clockwise rotation angle in degrees.
Example – render a rotated label with a pill-shaped highlight:
class RibbonLabelPlotBand extends PlotBand {
const RibbonLabelPlotBand()
: super(text: 'Target Range', textAngle: 45);
@override
void drawText(Canvas canvas, Offset position, TextStyle style,
int angle) {
final TextPainter painter = TextPainter(
text: TextSpan(text: text),
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
)..layout();
final Offset center =
position + Offset(painter.width / 2, painter.height / 2);
canvas.save();
canvas.translate(center.dx, center.dy);
canvas.rotate(angle * (pi / 180));
final Rect capsule = Rect.fromCenter(
center: Offset.zero,
width: painter.width + 12,
height: painter.height + 8,
);
canvas.drawRRect(
RRect.fromRectAndRadius(capsule, const Radius.circular(12)),
Paint()..color = Colors.deepPurple.withAlpha(115),
);
painter.paint(canvas,
Offset(-painter.width / 2, -painter.height / 2));
canvas.restore();
}
}
Implementation
void drawText(Canvas canvas, Offset position, TextStyle style, int angle) {
if (text == null || text!.isEmpty) {
return;
}
final TextSpan span = TextSpan(text: text, style: style);
final TextPainter textPainter = TextPainter(
text: span,
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
);
textPainter.layout();
if (angle == 0) {
textPainter.paint(canvas, position);
} else {
final double halfWidth = textPainter.width / 2;
final double halfHeight = textPainter.height / 2;
canvas
..save()
..translate(position.dx + halfWidth, position.dy + halfHeight)
..rotate(degreesToRadians(angle.toDouble()));
textPainter.paint(canvas, Offset(-halfWidth, -halfHeight));
canvas.restore();
}
}