Flutter textpainter example

Flutter TextPainter Example

The TextPainter class in Flutter allows you to measure and paint text on a canvas. It provides various methods to determine the size and layout of text, as well as custom painting options.

Example Code:


import 'package:flutter/material.dart';

class TextPainterExample extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final textSpan = TextSpan(
      text: 'Hello, Flutter!',
      style: TextStyle(
        color: Colors.black,
        fontSize: 20,
        fontWeight: FontWeight.bold,
      ),
    );
    
    final textPainter = TextPainter(
      text: textSpan,
      textAlign: TextAlign.center,
      textDirection: TextDirection.ltr,
    );
    
    textPainter.layout(maxWidth: size.width);
    final offsetX = (size.width - textPainter.width) / 2;
    final offsetY = (size.height - textPainter.height) / 2;
    final offset = Offset(offsetX, offsetY);
    
    textPainter.paint(canvas, offset);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: CustomPaint(
        painter: TextPainterExample(),
      ),
    ),
  ));
}
  

In this example, we create a custom painter called TextPainterExample that extends the CustomPainter class. Inside the paint method, we define a TextSpan with the desired text, style, and alignment.

We then create an instance of TextPainter with the defined TextSpan, setting the text alignment and direction. After that, we use the layout method to calculate the dimensions of the text based on the given maximum width.

To center the text horizontally and vertically on the canvas, we calculate the appropriate offsets using the canvas size and the text dimensions. Finally, we use the paint method of TextPainter to actually draw the text on the canvas.

In the main function, we wrap the CustomPaint widget with a Scaffold and display it using runApp.

Leave a comment