Flutter-CustomPaint和CustomPainter

配图来自网络,如侵必删

Flutter开发中,我们可能用自定义画布实现动画效果绘制。自定义画布主要涉及到CustomPaintCustomPainter,这篇文章主要分享这两个类,希望对小伙伴们有所帮助。

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的时候必须要重写它的paintshouldRepaint接口,我们可以根据场景来选择性的重写hitTestshouldRebuildSemantics方法。

自定义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;
  }
}

这是最简单的实现。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容