shouldRepaint method

  1. @override
bool shouldRepaint(
  1. covariant ImageEditorPainter oldDelegate
)
override

Called whenever a new instance of the custom painter delegate class is provided to the RenderCustomPaint object, or any time that a new CustomPaint object is created with a new instance of the custom painter delegate class (which amounts to the same thing, because the latter is implemented in terms of the former).

If the new instance represents different information than the old instance, then the method should return true, otherwise it should return false.

If the method returns false, then the paint call might be optimized away.

It's possible that the paint method will get called even if shouldRepaint returns false (e.g. if an ancestor or descendant needed to be repainted). It's also possible that the paint method will get called without shouldRepaint being called at all (e.g. if the box changes size).

If a custom delegate has a particularly expensive paint function such that repaints should be avoided as much as possible, a RepaintBoundary or RenderRepaintBoundary (or other render object with RenderObject.isRepaintBoundary set to true) might be helpful.

The oldDelegate argument will never be null.

Implementation

@override
bool shouldRepaint(ImageEditorPainter oldDelegate) {
  // 只有当关键状态发生变化时才重绘
  final oldController = oldDelegate.controller;
  final newController = controller;

  // 检查图片是否变化
  if (oldController.image != newController.image) return true;

  // 检查旋转角度是否变化
  if (oldController.currentRotationAngle != newController.currentRotationAngle) return true;

  // 检查缩放是否变化
  if ((oldController.scale - newController.scale).abs() > 0.001) return true;

  // 检查裁剪框是否变化
  if (oldController.cropRect != newController.cropRect) return true;

  // 检查工具是否变化
  if (oldController.activeTool != newController.activeTool) return true;

  // 检查文本图层是否变化
  if (oldController.textLayers.length != newController.textLayers.length) return true;
  if (oldController.selectedTextLayerId != newController.selectedTextLayerId) return true;

  // 检查文本图层内容是否变化(简化检查:只检查数量和选中状态)
  for (int i = 0; i < oldController.textLayers.length; i++) {
    final oldLayer = oldController.textLayers[i];
    final newLayer = newController.textLayers[i];
    if (oldLayer.id != newLayer.id ||
        oldLayer.text != newLayer.text ||
        oldLayer.position != newLayer.position ||
        oldLayer.color != newLayer.color ||
        (oldLayer.fontSize - newLayer.fontSize).abs() > 0.1) {
      return true;
    }
  }

  return false;
}