flutter 绘制文本 / 阴影

421 阅读1分钟

WechatIMG25.jpeg

import 'dart:math';
import 'package:flutter/material.dart';

class DrawTextPage extends StatelessWidget {
  const DrawTextPage({super.key});

  @override
  Widget build(BuildContext context) {

    return Material(
      color: Colors.white,
      child: Center(
        child: Container(
          width: 300,
          height: 300,
          color: Colors.red,
          child: CustomPaint(
            painter: DrawTextPaint(),
          ),
        ),
      ),
    );
  }
}

class DrawTextPaint extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {

    print("======size===${size}");

    var width = size.width;
    var height = size.height;
    //移动(0,0)点到中心
    canvas.save();
    canvas.translate(size.width/2,size.height/2);
    var textPainter = TextPainter(textDirection: TextDirection.ltr);
    textPainter.text =  TextSpan(text: '1000000',
      style: TextStyle(color: Colors.blue,
          shadows:  <Shadow>[
            const Shadow(
              offset: Offset(4.0, 4.0),
              blurRadius: 3.0,
              color: Color.fromARGB(99, 64, 64, 64),
            ),
            Shadow(
                offset:  const Offset(1.0, 1.0),
                blurRadius: 8.0,
                color: Colors.grey.shade100),
          ],
          fontSize: 20),

    );
    textPainter.layout(maxWidth: width);
    canvas.rotate(pi/4);
    textPainter.paint(canvas,Offset(-textPainter.width/2,-textPainter.height/2));
    canvas.restore();

    canvas.save();
    canvas.translate(size.width/2,size.height/4);
    var textPainter1 = TextPainter(textDirection: TextDirection.ltr);
    textPainter1.text =  TextSpan(text: '2000000', style: TextStyle(color: Colors.green
        , fontSize: 20,
        shadows:  <Shadow>[
          const Shadow(
            offset: Offset(4.0, 4.0),
            blurRadius: 3.0,
            color: Color.fromARGB(99, 64, 64, 64),
          ),
          Shadow(
              offset:  const Offset(1.0, 1.0),
              blurRadius: 8.0,
              color: Colors.lightBlue.shade100),
        ]
    ));
    textPainter1.layout(maxWidth: width);
    canvas.rotate(-pi/4);
    textPainter1.paint(canvas,Offset(-textPainter.width/2,-textPainter.height/2));
    canvas.restore();

    canvas.save();
    canvas.translate(size.width/2,size.height * 3/4);
    var textPainter2 = TextPainter(textDirection: TextDirection.ltr);
    textPainter2.text = const TextSpan(text: '3000000', style: TextStyle(color: Colors.yellow, fontSize: 20));
    textPainter2.layout(maxWidth: width);
    canvas.rotate(-pi/4);
    textPainter2.paint(canvas,Offset(-textPainter.width/2,-textPainter.height/2));
    canvas.restore();
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }

}