paint method

  1. @override
void paint(
  1. Canvas canvas,
  2. Size size
)
override

Called whenever the object needs to paint. The given Canvas has its coordinate space configured such that the origin is at the top left of the box. The area of the box is the size of the size argument.

Paint operations should remain inside the given area. Graphical operations outside the bounds may be silently ignored, clipped, or not clipped. It may sometimes be difficult to guarantee that a certain operation is inside the bounds (e.g., drawing a rectangle whose size is determined by user inputs). In that case, consider calling Canvas.clipRect at the beginning of paint so everything that follows will be guaranteed to only draw within the clipped area.

Implementations should be wary of correctly pairing any calls to Canvas.save/Canvas.saveLayer and Canvas.restore, otherwise all subsequent painting on this canvas may be affected, with potentially hilarious but confusing results.

To paint text on a Canvas, use a TextPainter.

To paint an image on a Canvas:

  1. Obtain an ImageStream, for example by calling ImageProvider.resolve on an AssetImage or NetworkImage object.

  2. Whenever the ImageStream's underlying ImageInfo object changes (see ImageStream.addListener), create a new instance of your custom paint delegate, giving it the new ImageInfo object.

  3. In your delegate's paint method, call the Canvas.drawImage, Canvas.drawImageRect, or Canvas.drawImageNine methods to paint the ImageInfo.image object, applying the ImageInfo.scale value to obtain the correct rendering size.

Implementation

@override
void paint(Canvas canvas, Size size) {
  if (faces.isEmpty) return;

  final ui.Paint boxPaint = Paint()
    ..style = PaintingStyle.stroke
    ..strokeWidth = boundingBoxThickness
    ..color = boundingBoxColor;

  final ui.Paint detKpPaint = Paint()
    ..style = PaintingStyle.fill
    ..color = landmarkColor;

  final ui.Paint meshPaint = Paint()
    ..style = PaintingStyle.fill
    ..color = meshColor;

  final ui.Paint irisFill = Paint()
    ..style = PaintingStyle.fill
    ..color = irisColor.withAlpha(153)
    ..blendMode = BlendMode.srcOver;

  final ui.Paint irisStroke = Paint()
    ..style = PaintingStyle.stroke
    ..strokeWidth = 1.5
    ..color = irisColor.withAlpha(230);

  final double ox = imageRectOnCanvas.left;
  final double oy = imageRectOnCanvas.top;
  final double scaleX = imageRectOnCanvas.width / originalImageSize.width;
  final double scaleY = imageRectOnCanvas.height / originalImageSize.height;

  for (final Face face in faces) {
    if (showBoundingBoxes) {
      final BoundingBox boundingBox = face.boundingBox;
      final ui.Rect rect = Rect.fromLTRB(
        ox + boundingBox.topLeft.x * scaleX,
        oy + boundingBox.topLeft.y * scaleY,
        ox + boundingBox.bottomRight.x * scaleX,
        oy + boundingBox.bottomRight.y * scaleY,
      );
      canvas.drawRect(rect, boxPaint);
    }

    if (showPoseAndScores || showClassification) {
      final BoundingBox bb = face.boundingBox;
      final ui.Rect faceRect = Rect.fromLTRB(
        ox + bb.topLeft.x * scaleX,
        oy + bb.topLeft.y * scaleY,
        ox + bb.bottomRight.x * scaleX,
        oy + bb.bottomRight.y * scaleY,
      );
      drawFaceInfoLabel(
        canvas,
        size,
        face,
        faceRect,
        showClassification: showClassification,
      );
    }

    if (showLandmarks) {
      const labelNames = {
        FaceLandmarkType.leftEye: 'Left Eye',
        FaceLandmarkType.rightEye: 'Right Eye',
        FaceLandmarkType.noseTip: 'Nose Tip',
        FaceLandmarkType.mouth: 'Mouth',
        FaceLandmarkType.leftEyeTragion: 'L Tragion',
        FaceLandmarkType.rightEyeTragion: 'R Tragion',
      };

      for (final entry in face.landmarks.toMap().entries) {
        final p = entry.value;
        final center = Offset(ox + p.x * scaleX, oy + p.y * scaleY);
        canvas.drawCircle(center, landmarkSize, detKpPaint);

        if (showLandmarkLabels) {
          final label = labelNames[entry.key] ?? entry.key.name;
          final textPainter = TextPainter(
            text: TextSpan(
              text: label,
              style: const TextStyle(
                color: Colors.white,
                fontSize: 10,
                fontWeight: FontWeight.w600,
              ),
            ),
            textDirection: TextDirection.ltr,
          )..layout();

          const double paddingH = 6;
          const double paddingV = 3;
          const double arrowHeight = 5;
          const double arrowHalfWidth = 4;
          const double gap = 2;

          final double boxWidth = textPainter.width + paddingH * 2;
          final double boxHeight = textPainter.height + paddingV * 2;
          final double tipY = center.dy - landmarkSize - gap;
          final double boxBottom = tipY - arrowHeight;
          final double boxTop = boxBottom - boxHeight;
          final double boxLeft = center.dx - boxWidth / 2;
          final double boxRight = center.dx + boxWidth / 2;

          final bgPaint = Paint()..color = landmarkColor;
          final rrect = RRect.fromLTRBR(
            boxLeft,
            boxTop,
            boxRight,
            boxBottom,
            const Radius.circular(4),
          );
          canvas.drawRRect(rrect, bgPaint);

          final arrowPath = Path()
            ..moveTo(center.dx - arrowHalfWidth, boxBottom)
            ..lineTo(center.dx, tipY)
            ..lineTo(center.dx + arrowHalfWidth, boxBottom)
            ..close();
          canvas.drawPath(arrowPath, bgPaint);

          textPainter.paint(
            canvas,
            Offset(boxLeft + paddingH, boxTop + paddingV),
          );
        }
      }
    }

    if (showMesh) {
      final FaceMesh? faceMesh = face.mesh;
      if (faceMesh != null) {
        final mesh = faceMesh.points;
        final double imgArea =
            imageRectOnCanvas.width * imageRectOnCanvas.height;
        final double radius = meshSize + math.sqrt(imgArea) / 1000.0;

        for (final p in mesh) {
          canvas.drawCircle(
            Offset(ox + p.x * scaleX, oy + p.y * scaleY),
            radius,
            meshPaint,
          );
        }
      }
    }

    if (showIrises || showEyeContours || showEyeMesh) {
      final eyePair = face.eyes;
      if (eyePair != null) {
        for (final iris in [eyePair.leftEye, eyePair.rightEye]) {
          if (iris == null) continue;

          if (showIrises) {
            final bounds = boundsOf(
              [
                iris.irisCenter,
                ...iris.irisContour,
              ].map((p) => Offset(ox + p.x * scaleX, oy + p.y * scaleY)),
            );
            canvas.drawOval(bounds, irisFill);
            canvas.drawOval(bounds, irisStroke);
          }

          if (showEyeContours && iris.mesh.isNotEmpty) {
            final Paint eyeOutlinePaint = Paint()
              ..color = eyeContourColor
              ..style = PaintingStyle.stroke
              ..strokeWidth = 1.5;

            final eyelidContour = iris.contour;
            for (final connection in eyeLandmarkConnections) {
              if (connection[0] < eyelidContour.length &&
                  connection[1] < eyelidContour.length) {
                final p1 = eyelidContour[connection[0]];
                final p2 = eyelidContour[connection[1]];

                canvas.drawLine(
                  Offset(ox + p1.x * scaleX, oy + p1.y * scaleY),
                  Offset(ox + p2.x * scaleX, oy + p2.y * scaleY),
                  eyeOutlinePaint,
                );
              }
            }
          }

          if (showEyeMesh && iris.mesh.isNotEmpty) {
            final Paint eyeMeshPointPaint = Paint()
              ..color = eyeMeshColor
              ..style = PaintingStyle.fill;

            for (final p in iris.mesh) {
              final canvasX = ox + p.x * scaleX;
              final canvasY = oy + p.y * scaleY;
              canvas.drawCircle(
                Offset(canvasX, canvasY),
                eyeMeshSize,
                eyeMeshPointPaint,
              );
            }
          }
        }
      }
    }
  }
}