Flutter自定义绘制Widget初探
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('自定义绘制Widget'),
),
body: Center(
child: CustomPaint(
size: Size(200, 200),
painter: MyPainter(),
),
),
);
}
}
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.blue
..strokeWidth = 4.0
..style = PaintingStyle.stroke;
canvas.drawLine(Offset(0, size.height / 2), Offset(size.width, size.height / 2), paint);
canvas.drawLine(Offset(size.width / 2, 0), Offset(size.width / 2, size.height), paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
这段代码创建了一个简单的Flutter应用,其中包含了一个自定义绘制的Widget。MyPainter
类继承自CustomPainter
,并重写了paint
方法来绘制一个矩形。shouldRepaint
返回false
意味着只会绘制一次,后续重绘时不会再调用paint
方法。这个例子展示了如何在Flutter中使用自定义绘制,并且是学习Flutter绘图框架的一个很好的起点。
评论已关闭