class CustomPaintWidget extends StatefulWidget {
const CustomPaintWidget({Key? key}) : super(key: key);
@override
State<CustomPaintWidget> createState() {
return CustomPaintState();
}
}
class CustomPaintState extends State<CustomPaintWidget> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("CustomPaint和Canvas")),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CustomPaint(
size: const Size(300, 300),
painter: MyPainter(),
),
ElevatedButton(
onPressed: () {},
child: const Text("刷新"),
),
],
),
),
);
}
}
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
var rect = Offset.zero & size;
//画棋盘
drasChessBoard(canvas, rect);
//画棋子
drawPieces(canvas, rect);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
//画棋盘
void drasChessBoard(Canvas canvas, Rect rect) {
//棋盘背景
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);
}
}
//棋子
void drawPieces(Canvas canvas, Rect rect) {
double eWidth = rect.width / 15;
double eHeight = rect.height / 15;
//黑子
var paint = Paint()
..style = PaintingStyle.fill
..color = Colors.black;
canvas.drawCircle(
Offset(rect.center.dx - eWidth / 2, rect.center.dy - eHeight / 2),
min(eWidth / 2, eHeight / 2) - 2,
paint);
paint.color = Colors.white;
canvas.drawCircle(
Offset(rect.center.dx + eWidth / 2, rect.center.dy - eHeight / 2),
min(eWidth / 2, eHeight / 2) - 2,
paint);
}
}
Flutter CustomPaint 与 Canvas
猜你喜欢
转载自blog.csdn.net/xiaopihair123/article/details/125018016
今日推荐
周排行