Flutter自定义View

第一章 入门案例

我们来画一个饼状图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
///第一个自定义view,需事先两个方法
/// paint方法,在这里实现绘制逻辑
/// shouldRepaint() 是否需要重绘
class WheelView extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
double wheelSize = min(size.width, size.height) / 2; //取宽高的最小值
double count = 6;
double radius = 2 * pi / count; //角度
Rect rect = Rect.fromCircle(
center: Offset(wheelSize, wheelSize), radius: wheelSize);
//每次画 1/6 个圆弧
///参数1:rect:基于矩形内部绘制圆弧
///参数2:startAngle 参数3:sweepAngle 参数4:useCenter 参数5:Paint
canvas.drawArc(rect, 0, radius, true, getPaint(Colors.orange));
canvas.drawArc(rect, radius, radius, true, getPaint(Colors.black38));
canvas.drawArc(rect, radius * 2, radius, true, getPaint(Colors.green));
canvas.drawArc(rect, radius * 3, radius, true, getPaint(Colors.red));
canvas.drawArc(rect, radius * 4, radius, true, getPaint(Colors.blue));
canvas.drawArc(rect, radius * 5, radius, true, getPaint(Colors.pink));
}

@override
bool shouldRepaint(covariant CustomPainter oldDelegate) =>
oldDelegate != this;

Paint getPaint(Color color) {
Paint paint = Paint();
paint.color = color;
return paint;
}
}

将饼状图包装成一个新的控件

1
2
3
4
5
6
7
8
9
10
class CakeView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return CustomPaint(
///将绘制的内容设置给CustomPaint的painter属性
painter: WheelView(),
size: Size(200, 200),
);
}
}