//customPaint widget
//foregroundPaint CustomPainter的实现类
//在子类中canvas和paint配合进行原的绘制
class CustomCirclePage extends StatefulWidget {
@override
_CustomCirclePageState createState() => _CustomCirclePageState();
}
class _CustomCirclePageState extends State<CustomCirclePage> with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation _animation;
@override
void initState() {
super.initState();
_controller = new AnimationController(vsync: this, duration: Duration(seconds: 3));
_animation = Tween<double>(begin: 0.0, end: 100.0).animate(_controller);
// ..addListener(() {
// setState(() {});
// });
_controller.repeat();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('自绘Circle'),
),
body: Container(
child: Center(
child: Container(
width: 200,
height: 200,
color: Colors.blue,
child: CustomPaint(
size: Size(200, 200),
foregroundPainter: AnimatedPainter(_animation),
),
),
),
));
}
@override
void dispose() {
_controller?.dispose();
super.dispose();
}
}
class AnimatedPainter extends CustomPainter {
Paint _paint = Paint()
..color = Colors.redAccent
..strokeWidth = 4
..style = PaintingStyle.stroke;
Animation animation;
AnimatedPainter(this.animation);
@override
void paint(Canvas canvas, Size size) {
// 这里的offset是以自定义控件的左上角位置为零点位置进行偏移的
canvas.drawCircle(Offset(100, 100), animation.value * 1.0, _paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
步骤:
1. 利用 CustomPaint 构建需要绘制的对象,构造方法中的 foregroundPainter 用于接收自定义Painter。
2. 定义继承抽象类 CustomPainter 类的 AnimatedPainter 类,实现 shouldRepaint 方法和 paint 方法,paint 方法中有 Canvas 参数对象,利用该对象可以进行想要的任何绘制操作。