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 the widget has a zero size side then we cannot continue painting.
  if (size.shortestSide == 0) {
    debugPrint(
        "[QR] WARN: width or height is zero. You should set a 'size' value "
        'or nest this painter in a Widget that defines a non-zero size');
    return;
  }

  final paintMetrics = _PaintMetrics(
    containerSize: size.shortestSide,
    moduleCount: _qr!.moduleCount,
    gapSize: gapless ? 0 : _gapSize,
  );

  // draw the finder pattern elements
  _drawFinderPatternItem(
    FinderPatternPosition.topLeft,
    canvas,
    paintMetrics,
  );
  _drawFinderPatternItem(
    FinderPatternPosition.bottomLeft,
    canvas,
    paintMetrics,
  );
  _drawFinderPatternItem(
    FinderPatternPosition.topRight,
    canvas,
    paintMetrics,
  );
  bool isCenterModule(int x, int y) {
    // Calculate the coordinates of the center module(s)
    var center = _qr!.moduleCount ~/ 2; // Integer division
    var range = 3; // Adjust the range as needed

    // Check if the current module is within the excluded range around the center
    return x >= center - range &&
        x <= center + range &&
        y >= center - range &&
        y <= center + range;
  }

  Size? embeddedImageSize;
  Offset? embeddedImagePosition;
  Offset? safeAreaPosition;
  Rect? safeAreaRect;
  if (embeddedImage != null || drawCircle) {
    final originalSize = Size(
      embeddedImage?.width.toDouble() ?? embeddedImageStyle.size!.width,
      embeddedImage?.height.toDouble() ?? embeddedImageStyle.size!.height,
    );
    final requestedSize = embeddedImageStyle.size;
    embeddedImageSize = _scaledAspectSize(size, originalSize, requestedSize);
    embeddedImagePosition = Offset(
      (size.width - embeddedImageStyle.size!.width) / 2.0,
      (size.height - embeddedImageStyle.size!.height) / 2.0,
    );
    if (embeddedImageStyle.safeArea) {
      final safeAreaMultiplier = embeddedImageStyle.safeAreaMultiplier;
      safeAreaPosition = Offset(
        (size.width - embeddedImageStyle.size!.width * safeAreaMultiplier) /
            2.0,
        (size.height - embeddedImageStyle.size!.height * safeAreaMultiplier) /
            2.0,
      );
      safeAreaRect = Rect.fromLTWH(
        safeAreaPosition.dx,
        safeAreaPosition.dy,
        embeddedImageStyle.size!.width * safeAreaMultiplier,
        embeddedImageStyle.size!.height * safeAreaMultiplier,
      );
    }

    if (embeddedImageStyle.embeddedImageShape != EmbeddedImageShape.none) {
      final color = _priorityColor(embeddedImageStyle.shapeColor);

      final squareRect = Rect.fromLTWH(
        embeddedImagePosition.dx,
        embeddedImagePosition.dy,
        embeddedImageStyle.size!.width,
        embeddedImageStyle.size!.height,
      );

      final paint = Paint()..color = color;

      switch (embeddedImageStyle.embeddedImageShape) {
        case EmbeddedImageShape.square:
          if (embeddedImageStyle.borderRadius > 0) {
            final roundedRect = RRect.fromRectAndRadius(
              squareRect,
              Radius.circular(embeddedImageStyle.borderRadius),
            );
            canvas.drawRRect(roundedRect, paint);
          } else {
            canvas.drawRect(squareRect, paint);
          }
          break;
        case EmbeddedImageShape.circle:
          final roundedRect = RRect.fromRectAndRadius(
              squareRect, Radius.circular(squareRect.width / 2));
          canvas.drawRRect(roundedRect, paint);
          break;
        default:
          break;
      }
    }
  }

  final gap = !gapless ? _gapSize : 0;
  // get the painters for the pixel information
  final pixelPaint = _paintCache.firstPaint(QrCodeElement.codePixel);
  pixelPaint!.color = _priorityColor(dataModuleStyle.color);

  final emptyPixelPaint =
      _paintCache.firstPaint(QrCodeElement.codePixelEmpty);
  emptyPixelPaint!.color = _qrDefaultEmptyColor;

  final borderRadius = Radius.circular(dataModuleStyle.borderRadius);
  final outsideBorderRadius =
      Radius.circular(dataModuleStyle.outsideBorderRadius);
  final isRoundedOutsideCorners = dataModuleStyle.roundedOutsideCorners;

  for (var x = 0; x < _qr!.moduleCount; x++) {
    for (var y = 0; y < _qr!.moduleCount; y++) {
      // draw the finder patterns independently
      if (_isFinderPatternPosition(x, y)) {
        continue;
      }
      // Skip drawing if the module is at the center
      // if (isCenterModule(x, y)) {
      //   x = x - 4;
      //   y = y - 4;
      // }
      final isDark = _qrImage.isDark(y, x);
      final paint = isDark ? pixelPaint : emptyPixelPaint;
      if (!isDark && !isRoundedOutsideCorners) {
        continue;
      }
      // paint a pixel
      final squareRect = _createDataModuleRect(paintMetrics, x, y, gap);
      // check safeArea
      if (embeddedImageStyle.safeArea &&
          safeAreaRect?.overlaps(squareRect) == true) continue;
      switch (dataModuleStyle.dataModuleShape) {
        case QrDataModuleShape.square:
          if (dataModuleStyle.borderRadius > 0) {
            // If pixel isDark == true and outside safe area
            // than can't be rounded
            final isDarkLeft =
                _isDarkOnSide(x - 1, y, safeAreaRect, paintMetrics, gap);
            final isDarkTop =
                _isDarkOnSide(x, y - 1, safeAreaRect, paintMetrics, gap);
            final isDarkRight =
                _isDarkOnSide(x + 1, y, safeAreaRect, paintMetrics, gap);
            final isDarkBottom =
                _isDarkOnSide(x, y + 1, safeAreaRect, paintMetrics, gap);

            if (!isDark && isRoundedOutsideCorners) {
              final isDarkTopLeft = _isDarkOnSide(
                  x - 1, y - 1, safeAreaRect, paintMetrics, gap);
              ;
              final isDarkTopRight = _isDarkOnSide(
                  x + 1, y - 1, safeAreaRect, paintMetrics, gap);
              ;
              final isDarkBottomLeft = _isDarkOnSide(
                  x - 1, y + 1, safeAreaRect, paintMetrics, gap);
              ;
              final isDarkBottomRight = _isDarkOnSide(
                  x + 1, y + 1, safeAreaRect, paintMetrics, gap);
              ;

              final roundedRect = RRect.fromRectAndCorners(
                squareRect,
                topLeft: isDarkTop && isDarkLeft && isDarkTopLeft
                    ? outsideBorderRadius
                    : Radius.zero,
                topRight: isDarkTop && isDarkRight && isDarkTopRight
                    ? outsideBorderRadius
                    : Radius.zero,
                bottomLeft: isDarkBottom && isDarkLeft && isDarkBottomLeft
                    ? outsideBorderRadius
                    : Radius.zero,
                bottomRight: isDarkBottom && isDarkRight && isDarkBottomRight
                    ? outsideBorderRadius
                    : Radius.zero,
              );
              canvas.drawPath(
                Path.combine(
                  PathOperation.difference,
                  Path()..addRect(squareRect),
                  Path()
                    ..addRRect(roundedRect)
                    ..close(),
                ),
                pixelPaint,
              );
            } else {
              final roundedRect = RRect.fromRectAndCorners(
                squareRect,
                topLeft: isDarkTop || isDarkLeft ? Radius.zero : borderRadius,
                topRight:
                    isDarkTop || isDarkRight ? Radius.zero : borderRadius,
                bottomLeft:
                    isDarkBottom || isDarkLeft ? Radius.zero : borderRadius,
                bottomRight:
                    isDarkBottom || isDarkRight ? Radius.zero : borderRadius,
              );
              canvas.drawRRect(roundedRect, paint);
            }
          } else {
            canvas.drawRect(squareRect, paint);
          }
          break;
        default:
          final roundedRect = RRect.fromRectAndRadius(
              squareRect, Radius.circular(squareRect.width / 2));
          canvas.drawRRect(roundedRect, paint);
          break;
      }
    }
  }

  // set gradient for all
  if (gradient != null) {
    final paintGradient = Paint();
    paintGradient.shader =
        gradient!.createShader(Rect.fromLTWH(0, 0, size.width, size.height));
    paintGradient.blendMode = BlendMode.values[12];
    canvas.drawRect(
      Rect.fromLTWH(
        paintMetrics.inset,
        paintMetrics.inset,
        paintMetrics.innerContentSize,
        paintMetrics.innerContentSize,
      ),
      paintGradient,
    );
  }

  // draw the image overlay.
  if (embeddedImage != null) {
    _drawImageOverlay(
      canvas,
      embeddedImagePosition!,
      embeddedImageSize!,
      embeddedImageStyle,
    );
  }
  if (drawCircle) {
    _drawEmptyCircle(
      canvas,
      embeddedImagePosition!,
      embeddedImageSize!,
      embeddedImageStyle,
    );
  }
}