一,概念
CustomPaint是画布,画布包含CustomPainter内容,CustomPainter需要有画笔Paint和画画的形状(画画的形状由canvas提供)
二,代码角度理解
import 'package:flutter/material.dart';
main() {
runApp(const MaterialApp(
home: H(),
));
}
class H extends StatelessWidget {
const H({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("draw_demo"),
),
body: Center(
child: CustomPaint(
size: const Size(300, 300), // 画布大小
painter: MyPainter()), // 绘制的内容,MyPainter继承自CustomPainter
));
}
}
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
Rect rect = const Rect.fromLTRB(0, 0, 300, 300); // 矩形在画布上的左上角x,y以及右下角x,y坐标
var painter = Paint() // 相当于是画笔,定义画笔什么颜色、怎么画(填充还是仅轮廓等)
..style = PaintingStyle.fill
..color = Colors.red;
canvas.drawRect(
rect, painter); // canvas提供api,到底画什么。如果是drawRect则传入Rect对象,用painter这根画笔
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false; // 如果绘制的东西会收到数据影响,则true
}
效果:

三,拓展的代码(动手敲一敲,会理解的)
import 'package:flutter/material.dart';
main() {
runApp(const MaterialApp(
home: H(),
));
}
class H extends StatelessWidget {
const H({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("draw_demo"),
),
body: Center(
child: CustomPaint(
size: const Size(300, 300), // 画布大小
painter: MyPainter()), // 绘制的内容,MyPainter继承自CustomPainter
));
}
}
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
Rect rect = const Rect.fromLTRB(0.0, 0.0, 300.0, 300.0);
// 背景
var paint = Paint() //背景画布的
..isAntiAlias = true
..style = PaintingStyle.fill
..color = const Color(0xffdcc48c);
canvas.drawRect(rect, paint);
// 网格
paint
..style = PaintingStyle.stroke
..color = Colors.black38
..strokeWidth = 1.0;
for (int i = 0; i <= 15; i++) {
//绘制横线
double dy = rect.top + rect.height / 15 * i;
canvas.drawLine(Offset(rect.left, dy), Offset(rect.right, dy), paint);
}
for (int i = 0; i <= 15; i++) {
//绘制竖线
double dx = rect.left + rect.width / 15 * i;
canvas.drawLine(Offset(dx, rect.top), Offset(dx, rect.bottom), paint);
}
// 黑子
paint = Paint()
..style = PaintingStyle.fill
..color = Colors.black;
canvas.drawCircle(const Offset(160, 160), 8, paint);
// 白子
paint = Paint()
..style = PaintingStyle.fill
..color = Colors.white;
canvas.drawCircle(const Offset(140, 140), 8, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
效果:

938

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



