本文同步发表于微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新
一、绘图的核心组件

二、CustomPaint 与 CustomPainter 使用
2.1 简单绘图示例
import 'dart:math' as math;
class BasicCanvasDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('基础画布')),
body: Center(
child: CustomPaint(
size: Size(300, 300), // 画布尺寸
painter: MyPainter(), // 自定义绘制器
),
),
);
}
}
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
// 1. 创建画笔
final paint = Paint()
..color = Colors.blue
..style = PaintingStyle.fill
..strokeWidth = 2;
// 2. 计算中心点
final center = Offset(size.width / 2, size.height / 2);
// 3. 绘制圆形
canvas.drawCircle(center, 100, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false; // 不需要重绘
}
}
2.2 CustomPainter 生命周期
class LifecyclePainter extends CustomPainter {
int paintCount = 0;
int repaintCount = 0;
@override
void paint(Canvas canvas, Size size) {
paintCount++;
print('第 $paintCount 次绘制');
// 绘制计数文本
final textStyle = TextStyle(color: Colors.black, fontSize: 20);
final textSpan = TextSpan(
text: '绘制次数: $paintCount\n重绘检查: $repaintCount',
style: textStyle,
);
final textPainter = TextPainter(
text: textSpan,
textDirection: TextDirection.ltr,
);
textPainter.layout();
textPainter.paint(canvas, Offset(10, 10));
}
@override
bool shouldRepaint(LifecyclePainter oldDelegate) {
repaintCount++;
// 复杂逻辑:当 paintCount 是 5 的倍数时重绘
bool needsRepaint = (paintCount % 5 == 0);
print('重绘检查: $needsRepaint');
return needsRepaint;
}
@override
bool? hitTest(Offset position) {
// 点击测试:返回 true 表示该点可以被点击
return null; // null 表示使用默认行为
}
@override
void addListener(VoidCallback listener) {
super.addListener(listener);
print('添加监听器');
}
@override
void removeListener(VoidCallback listener) {
super.removeListener(listener);
print('移除监听器');
}
}
三、Paint 画笔
3.1 画笔基本属性
class PaintDemoPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final center = Offset(size.width / 2, size.height / 2);
// 1. 基础画笔
final basicPaint = Paint()
..color = Colors.blue // 颜色
..style = PaintingStyle.fill // 样式:fill 填充,stroke 描边
..strokeWidth = 5.0 // 描边宽度
..isAntiAlias = true; // 抗锯齿
// 2. 颜色混合模式
final blendPaint = Paint()
..color = Colors.red
..blendMode = BlendMode.multiply; // 颜色混合模式
// 3. 描边样式
final strokePaint = Paint()
..color = Colors.green
..style = PaintingStyle.stroke
..strokeWidth = 10
..strokeCap = StrokeCap.round // 线帽:butt, round, square
..strokeJoin = StrokeJoin.round; // 连接处:miter, round, bevel
// 4. 颜色过滤器
final filterPaint = Paint()
..colorFilter = ColorFilter.mode(
Colors.blue,
BlendMode.srcIn, // 多种混合模式
);
// 5. 图像过滤器
final imageFilterPaint = Paint()
..imageFilter = ImageFilter.blur(
sigmaX: 5.0, // X轴模糊度
sigmaY: 5.0, // Y轴模糊度
);
// 6. 着色器
final shaderPaint = Paint()
..shader = LinearGradient(
colors: [Colors.red, Colors.yellow, Colors.green],
stops: [0.0, 0.5, 1.0],
).createShader(Rect.fromCircle(
center: center,
radius: 100,
));
// 绘制示例
canvas.drawCircle(center, 100, basicPaint);
}
@override bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
3.2 高级 Paint 功能
class AdvancedPaintPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final center = Offset(size.width / 2, size.height / 2);
// 1. 虚线描边
final dashPaint = Paint()
..color = Colors.blue
..style = PaintingStyle.stroke
..strokeWidth = 3
..strokeCap = StrokeCap.round
..shader = null;
// 绘制虚线(通过Path实现)
final dashPath = Path()
..moveTo(50, 50)
..lineTo(size.width - 50, 50);
// 2. 渐变画笔
final gradientPaint = Paint()
..shader = RadialGradient(
colors: [Colors.red, Colors.orange, Colors.yellow],
stops: [0.0, 0.5, 1.0],
center: Alignment.center,
radius: 0.5,
tileMode: TileMode.clamp,
).createShader(Rect.fromCircle(center: center, radius: 100));
// 3. 图像画笔
final imagePaint = Paint()
..filterQuality = FilterQuality.high // 图像质量
..isAntiAlias = true;
// 4. 混合模式示例
final paints = [
Paint()..color = Colors.blue..blendMode = BlendMode.srcOver,
Paint()..color = Colors.red..blendMode = BlendMode.multiply,
Paint()..color = Colors.green..blendMode = BlendMode.screen,
Paint()..color = Colors.yellow..blendMode = BlendMode.overlay,
];
// 绘制不同混合模式的圆形
for (int i = 0; i < paints.length; i++) {
canvas.drawCircle(
Offset(80 + i * 70, 80),
30,
paints[i],
);
}
}
@override bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
四、Canvas 绘制方法
4.1 基本图形绘制
class BasicShapesPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.blue
..style = PaintingStyle.fill;
final strokePaint = Paint()
..color = Colors.red
..style = PaintingStyle.stroke
..strokeWidth = 3;
// 1. 绘制点
for (int i = 0; i < 10; i++) {
canvas.drawPoints(
PointMode.points,
[Offset(50 + i * 30, 50)],
strokePaint,
);
}
// 2. 绘制线
canvas.drawLine(
Offset(50, 100),
Offset(size.width - 50, 100),
strokePaint,
);
// 3. 绘制矩形
canvas.drawRect(
Rect.fromLTRB(50, 150, 150, 250),
paint,
);
// 4. 绘制圆角矩形
canvas.drawRRect(
RRect.fromLTRBR(200, 150, 300, 250, Radius.circular(20)),
paint,
);
// 5. 绘制圆形
canvas.drawCircle(
Offset(100, 350),
50,
paint,
);
// 6. 绘制椭圆
canvas.drawOval(
Rect.fromCenter(
center: Offset(250, 350),
width: 100,
height: 60,
),
paint,
);
// 7. 绘制圆弧
canvas.drawArc(
Rect.fromCircle(center: Offset(100, 500), radius: 50),
0, // 起始弧度
math.pi, // 扫过弧度(半圆)
true, // 是否使用中心点连接
paint,
);
// 8. 绘制阴影
canvas.drawShadow(
Path()
..addRRect(RRect.fromLTRBR(200, 450, 300, 550, Radius.circular(10))),
Colors.black,
10.0, // 模糊度
true, // 是否透明
);
}
@override bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
4.2 路径(Path)绘制
class PathPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.blue
..style = PaintingStyle.stroke
..strokeWidth = 3
..strokeCap = StrokeCap.round;
// 1. 基础路径
final trianglePath = Path()
..moveTo(100, 100) // 移动到起点
..lineTo(200, 100) // 画线到
..lineTo(150, 50) // 画线到
..close(); // 闭合路径
canvas.drawPath(trianglePath, paint);
// 2. 贝塞尔曲线
final curvePath = Path()
..moveTo(50, 200)
..quadraticBezierTo( // 二次贝塞尔曲线
150, 150, // 控制点
250, 200, // 终点
);
canvas.drawPath(curvePath, paint);
// 3. 三次贝塞尔曲线
final cubicPath = Path()
..moveTo(50, 300)
..cubicTo( // 三次贝塞尔曲线
100, 250, // 控制点1
200, 350, // 控制点2
250, 300, // 终点
);
canvas.drawPath(cubicPath, paint);
// 4. 圆弧路径
final arcPath = Path()
..moveTo(300, 100)
..arcTo(
Rect.fromCircle(center: Offset(350, 150), radius: 50),
0, // 起始弧度
math.pi / 2, // 扫过弧度
false, // 是否强制移动到圆弧起点
);
canvas.drawPath(arcPath, paint);
// 5. 路径操作
final complexPath = Path()
..moveTo(400, 100)
..relativeLineTo(50, 0) // 相对画线
..relativeLineTo(0, 50)
..relativeLineTo(-50, 0)
..close()
..addOval(Rect.fromCircle(center: Offset(450, 200), radius: 30))
..addRect(Rect.fromLTWH(420, 250, 60, 40))
..addRRect(RRect.fromLTRBR(420, 320, 480, 380, Radius.circular(10)));
canvas.drawPath(complexPath, paint);
// 6. 路径测量
final metrics = complexPath.computeMetrics();
double totalLength = 0;
for (var metric in metrics) {
totalLength += metric.length;
}
print('路径总长度: $totalLength');
}
@override bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
4.3 图像绘制
class ImagePainter extends CustomPainter {
final ui.Image? image;
ImagePainter(this.image);
@override
void paint(Canvas canvas, Size size) async {
if (image == null) return;
final paint = Paint()
..filterQuality = FilterQuality.high;
// 1. 基础绘制
canvas.drawImage(
image!,
Offset.zero,
paint,
);
// 2. 缩放绘制
canvas.drawImageRect(
image!,
Rect.fromLTWH(0, 0, image!.width.toDouble(), image!.height.toDouble()),
Rect.fromLTWH(0, 0, 100, 100),
paint,
);
// 3. 九宫格绘制
canvas.drawImageNine(
image!,
Rect.fromLTRB(20, 20, 40, 40), // 中心拉伸区域
Rect.fromLTRB(0, 150, 100, 250), // 目标区域
paint,
);
// 4. 使用 drawAtlas 绘制精灵图
final atlasPaint = Paint()
..blendMode = BlendMode.srcOver;
canvas.drawAtlas(
image!,
[
RSTransform.fromComponents(
rotation: 0,
scale: 1.0,
anchorX: 0,
anchorY: 0,
translateX: 0,
translateY: 300,
),
],
[
Rect.fromLTWH(0, 0, 50, 50), // 源矩形
],
[],
BlendMode.srcOver,
Rect.fromLTWH(0, 0, size.width, size.height),
atlasPaint,
);
}
@override bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
// 加载图像
Future<ui.Image> loadImage(BuildContext context) async {
final completer = Completer<ui.Image>();
final imageProvider = AssetImage('assets/image.png');
imageProvider.resolve(ImageConfiguration()).addListener(
ImageStreamListener((info, _) {
completer.complete(info.image);
}),
);
return completer.future;
}
4.4 文本绘制
class TextPainterDemo extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
// 1. 创建文本样式
final textStyle = TextStyle(
color: Colors.blue,
fontSize: 24,
fontWeight: FontWeight.bold,
fontFamily: 'Roboto',
letterSpacing: 1.2,
height: 1.5,
shadows: [
Shadow(
color: Colors.black.withOpacity(0.3),
offset: Offset(2, 2),
blurRadius: 3,
),
],
);
// 2. 创建文本段落
final textSpan = TextSpan(
text: 'Flutter Canvas\n文本绘制示例',
style: textStyle,
children: [
TextSpan(
text: '\n这是第二行',
style: textStyle.copyWith(
color: Colors.red,
fontSize: 18,
),
),
],
);
// 3. 创建 TextPainter
final textPainter = TextPainter(
text: textSpan,
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
maxLines: 3,
ellipsis: '...',
);
// 4. 布局文本(必须调用!)
textPainter.layout(
minWidth: 0,
maxWidth: size.width - 40, // 最大宽度
);
// 5. 绘制文本
textPainter.paint(
canvas,
Offset(20, 20), // 绘制位置
);
// 6. 获取文本尺寸信息
final textWidth = textPainter.width;
final textHeight = textPainter.height;
final didExceedMaxLines = textPainter.didExceedMaxLines;
print('文本宽度: $textWidth, 高度: $textHeight');
// 7. 获取光标位置
final position = TextPosition(offset: 5);
final offset = textPainter.getOffsetForCaret(position, Rect.zero);
print('第5个字符的位置: $offset');
// 8. 绘制背景框
final backgroundRect = Rect.fromLTWH(15, 15, textWidth + 10, textHeight + 10);
canvas.drawRect(
backgroundRect,
Paint()
..color = Colors.yellow.withOpacity(0.3)
..style = PaintingStyle.fill,
);
// 9. 绘制文本边界
canvas.drawRect(
Rect.fromLTWH(20, 20, textWidth, textHeight),
Paint()
..color = Colors.red
..style = PaintingStyle.stroke
..strokeWidth = 1,
);
}
@override bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
五、Canvas 变换与图层
5.1 图形变换
class TransformPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.blue
..style = PaintingStyle.fill;
final center = Offset(size.width / 2, size.height / 2);
// 保存当前画布状态
canvas.save();
// 1. 平移变换
canvas.translate(100, 100);
canvas.drawRect(Rect.fromLTWH(0, 0, 50, 50), paint);
// 2. 旋转变换
canvas.translate(100, 0);
canvas.rotate(math.pi / 4); // 旋转45度
canvas.drawRect(Rect.fromLTWH(0, 0, 50, 50), paint);
// 3. 缩放变换
canvas.restore(); // 恢复状态
canvas.save();
canvas.translate(100, 200);
canvas.scale(2.0, 0.5); // X轴放大2倍,Y轴缩小0.5倍
canvas.drawRect(Rect.fromLTWH(0, 0, 50, 50), paint);
// 4. 错切变换
canvas.restore();
canvas.save();
canvas.translate(200, 200);
canvas.skew(0.3, 0); // X轴错切
canvas.drawRect(Rect.fromLTWH(0, 0, 50, 50), paint);
// 5. 矩阵变换
canvas.restore();
canvas.save();
final matrix4 = Matrix4.identity()
..translate(300.0, 100.0)
..rotateZ(math.pi / 6)
..scale(1.5, 1.5);
canvas.transform(matrix4.storage);
canvas.drawRect(Rect.fromLTWH(0, 0, 50, 50), paint);
// 恢复画布状态
canvas.restore();
// 6. 获取当前变换矩阵
final currentMatrix = canvas.getTransform();
print('当前变换矩阵: $currentMatrix');
}
@override bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
5.2 图层与裁剪
class ClipPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.blue
..style = PaintingStyle.fill;
// 1. 矩形裁剪
canvas.save();
canvas.clipRect(Rect.fromLTRB(50, 50, 150, 150));
canvas.drawCircle(Offset(100, 100), 80, paint);
canvas.restore();
// 2. 圆角矩形裁剪
canvas.save();
canvas.clipRRect(
RRect.fromLTRBR(200, 50, 300, 150, Radius.circular(20)),
);
canvas.drawRect(Rect.fromLTRB(180, 30, 320, 170), paint);
canvas.restore();
// 3. 圆形裁剪
canvas.save();
canvas.clipPath(
Path()
..addOval(Rect.fromCircle(center: Offset(100, 250), radius: 50)),
);
canvas.drawRect(Rect.fromLTRB(30, 200, 170, 300), paint);
canvas.restore();
// 4. 路径裁剪
canvas.save();
final starPath = Path()
..moveTo(250, 250)
..lineTo(280, 310)
..lineTo(350, 310)
..lineTo(290, 340)
..lineTo(310, 400)
..lineTo(250, 360)
..lineTo(190, 400)
..lineTo(210, 340)
..lineTo(150, 310)
..lineTo(220, 310)
..close();
canvas.clipPath(starPath);
canvas.drawRect(Rect.fromLTRB(150, 200, 350, 400), paint);
canvas.restore();
// 5. 图层合成
canvas.saveLayer(
Rect.fromLTRB(50, 450, 200, 550),
Paint()..blendMode = BlendMode.multiply,
);
canvas.drawRect(
Rect.fromLTRB(50, 450, 200, 550),
Paint()..color = Colors.red,
);
canvas.drawCircle(
Offset(150, 500),
50,
Paint()..color = Colors.green,
);
canvas.restore();
// 6. 快速拒绝(优化性能)
canvas.save();
final clipRect = Rect.fromLTRB(250, 450, 350, 550);
canvas.clipRect(clipRect);
// 检查是否需要绘制
if (canvas.quickReject(Rect.fromLTRB(0, 0, 100, 100))) {
print('区域被裁剪,无需绘制');
} else {
canvas.drawRect(Rect.fromLTRB(240, 440, 360, 560), paint);
}
canvas.restore();
}
@override bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

3万+


与画笔(Paint)&spm=1001.2101.3001.11974&articleId=155646611&d=1&t=3&u=244cc0e997dc4eae8a21b1bba51e0df6)

被折叠的 条评论
为什么被折叠?



