
配图来自网络,如侵必删
在Flutter开发中,我们可能用自定义画布实现动画效果绘制。自定义画布主要涉及到CustomPaint和CustomPainter,这篇文章主要分享这两个类,希望对小伙伴们有所帮助。
CustomPaint
源码如下:
const CustomPaint({
Key? key,
this.painter,
this.foregroundPainter,
this.size = Size.zero,
this.isComplex = false,
this.willChange = false,
Widget? child,
}) : assert(size != null),
assert(isComplex != null),
assert(willChange != null),
assert(painter != null || foregroundPainter != null || (!isComplex && !willChange)),
super(key: key, child: child);
属性说明:
| 属性 | 属性详情 |
|---|---|
| painter | 负责绘制背景的painter |
| foregroundPainter | 负责绘制前景的painter |
| size | 组件的大小 |
| isComplex | 是否复杂绘制,需要用cache来提高绘制效率 |
| willChange | 和isComplex配合使用,当启用缓存时,该属性代表在下一帧中绘制是否会改变 |
| child | 子组件 |
CustomPainter
源码如下:
abstract class CustomPainter extends Listenable {
const CustomPainter({ Listenable? repaint }) : _repaint = repaint;
final Listenable? _repaint;
@override
void addListener(VoidCallback listener) => _repaint?.addListener(listener);
@override
void removeListener(VoidCallback listener) => _repaint?.removeListener(listener);
void paint(Canvas canvas, Size size);
SemanticsBuilderCallback? get semanticsBuilder => null;
bool shouldRebuildSemantics(covariant CustomPainter oldDelegate) => shouldRepaint(oldDelegate);
bool shouldRepaint(covariant CustomPainter oldDelegate);
bool? hitTest(Offset position) => null;
@override
String toString() => '${describeIdentity(this)}(${ _repaint?.toString() ?? "" })';
}
CustomPaint的绘制过程都将会交给CustomPainter来完成,CustomPainter是个抽象接口,在子类化CustomPainter的时候必须要重写它的paint跟 shouldRepaint接口,我们可以根据场景来选择性的重写hitTest跟shouldRebuildSemantics方法。
自定义CustomPainter
import 'package:flutter/cupertino.dart';
class MyCustomPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
// TODO: implement paint
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
// TODO: implement shouldRepaint
return false;
}
}
这是最简单的实现。