Flutter中如何在Canvas绘制的椭圆/圆形内部添加Icon图标
实现思路
系统自带的Material Icon本质是字体图标,你可以直接在CustomPainter的paint方法中通过TextPainter绘制该图标,完全不需要借助Stack组件,具体实现逻辑如下:
- 绘制完圆形边框后,先计算当前画布的中心点坐标
- 构造包含add图标字符的TextSpan,指定正确的图标字体配置、大小、颜色
- 使用TextPainter完成布局后,计算居中偏移量,直接绘制到Canvas上
完整可运行代码
import 'package:flutter/material.dart'; class CircleWithAddIcon extends CustomPainter { // 可自定义配置参数 final double iconSize; final Color iconColor; CircleWithAddIcon({ this.iconSize = 24, this.iconColor = Colors.black, }); @override void paint(Canvas canvas, Size size) { // 原有绘制圆形边框逻辑 final _paint = Paint() ..color = Colors.green ..strokeWidth = 6 ..style = PaintingStyle.stroke; canvas.drawOval( Rect.fromLTWH(0, 0, size.width, size.height), _paint, ); // 新增绘制居中add图标逻辑 final centerX = size.width / 2; final centerY = size.height / 2; // 构造图标对应的文本Span,直接调用系统图标配置 final iconSpan = TextSpan( text: String.fromCharCode(Icons.add.codePoint), style: TextStyle( fontFamily: Icons.add.fontFamily, fontPackage: Icons.add.fontPackage, color: iconColor, fontSize: iconSize, ), ); final textPainter = TextPainter( text: iconSpan, textDirection: TextDirection.ltr, ); // 计算图标实际尺寸 textPainter.layout(); // 计算居中偏移量,保证图标中心点和圆形中心点重合 final drawOffset = Offset( centerX - textPainter.width / 2, centerY - textPainter.height / 2, ); textPainter.paint(canvas, drawOffset); } @override bool shouldRepaint(CustomPainter oldDelegate) => false; }
补充说明
如果需要调整图标大小,直接修改传入的iconSize参数即可,注意不要超过圆形的内切矩形范围避免超出边框。如果需要绘制其他系统图标,只需要把代码中的Icons.add替换成对应的IconData即可。
内容的提问来源于stack exchange,提问作者Shistastic
相关产品推荐
相关产品推荐

